MATLAB: Does matlab work the next condition badly

condition if in vectorsMATLAB and Simulink Student Suite

Hi, I hope you all are well! My problem:
pitch=[10 -10];
delta_pitch_R14=[0.0409 0.0409];
delta_pitch_R23=[0.0407 0.0407];
if(pitch>=0)
pitch_real=pitch+(delta_pitch_R14+delta_pitch_R23)/2
else
pitch_real=pitch-(delta_pitch_R14+delta_pitch_R23)/2
end
pitch_real =
9.9592 -10.0408
But, the right answer is:
10.0408 -10.0408
Thanks!

Best Answer

The statement
if(pitch>=0)
is not being interpreted as you expect. It is not interpreted as an if statement for each element. Rather, it is interpreted as
if all(pitch>=0)
which is not true, so MATLAB executes the else portion.
See the documentation for if for details.
You could instead code this as
pitch=[10 -10];
delta_pitch_R14=[0.0409 0.0409];
delta_pitch_R23=[0.0407 0.0407];
positivePitchFactor = 2*(pitch>=0) - 1;
pitch_real = pitch + positivePitchFactor .* (delta_pitch_R14+delta_pitch_R23)/2;