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 10080x1. 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!

 Réponse acceptée

Stephen23
Stephen23 le 25 Mai 2019
Modifié(e) : Stephen23 le 25 Mai 2019

0 votes

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.

3 commentaires

Alexandros Katsikogiannis
Alexandros Katsikogiannis le 25 Mai 2019
Thank you so much Stephen! The max function made things quite easy. However, there are still times at which I need to compare values between arrays.
For example:
if A > 0
will be true when each element of A is above 0. Similarly if I set A > B (both are vectors), then the statement would be true only if all elements of A are bigger than B. How can modify this to get a true or false statement for each element respectively?
Forgive me for the vagueness, but my fundamentals are quite weak.
Alexandros Katsikogiannis
Alexandros Katsikogiannis le 25 Mai 2019
Nevermind, I managed to do it with a combination of "for" and "if" loop statements. Thanks again!
Stephen23
Stephen23 le 27 Mai 2019
Rather than using a loop, use logical indexing, as I showed in my answer.

Connectez-vous pour commenter.

Plus de réponses (1)

KALYAN ACHARJYA
KALYAN ACHARJYA le 25 Mai 2019
Modifié(e) : KALYAN ACHARJYA le 25 Mai 2019

0 votes

Your code doing the same
T_m=randi(6,1);
T_s=rand(6,1);
P=rand(6,1);
if T_m > T_s
P_actual = P - 0.3*(T_m - T_s);
else
P_actual = P;
end
Example 1: Here T_m>T_s
T_m =
1 2 3 4 5 6
T_s =
0.7224
0.1499
0.6596
0.5186
0.9730
0.6490
P =
0.8003
0.4538
0.4324
0.8253
0.0835
0.1332
P_actual =
0.7171 0.4171 0.1171 -0.1829 -0.4829 -0.7829
0.1988 -0.1012 -0.4012 -0.7012 -1.0012 -1.3012
0.3303 0.0303 -0.2697 -0.5697 -0.8697 -1.1697
0.6809 0.3809 0.0809 -0.2191 -0.5191 -0.8191
0.0754 -0.2246 -0.5246 -0.8246 -1.1246 -1.4246
0.0279 -0.2721 -0.5721 -0.8721 -1.1721 -1.4721
Example 2: Here T_m<=T_s (Else Condition P_actual = P)
T_m =
0.1734
0.3909
0.8314
0.8034
0.0605
0.3993
T_s =
1 2 3 4 5 6
P =
0.5269
0.4168
0.6569
0.6280
0.2920
0.4317
P_actual =
0.5269
0.4168
0.6569
0.6280
0.2920
0.4317

Catégories

En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by