MATLAB: If statement using vectors

if statement

Hello,
I am trying to make an if statement that will check the values of vector "T_m", element by element, with vector "T_s". All variables are vectors of the same length 10080×1. The result should be a vector as well. The values that "P_actual" attain are always equal to "P", even though there are times that T_m is higher than T_s.
Here is the code:
if T_m > T_s
P_actual = P – 0.3*(T_m – T_s);
else
P_actual = P;
end
I would appreciate any sort of help or tips!

Best Answer

You cannot use if like that to operate element-wise on arrays (read the if help to know what your code is actually doing). You could use a loop, but that would be pointlessly complex for this simple task.
Method one: indexing:
P_actual = P - 0.3*(T_m-T_s);
idx = T_m>T_s;
P_actual(~idx) = P(~idx)
Method two: max:
P_actual = P - 0.3*max(0,T_m-T_s)
I recommend using the max method.