If statement using vectors

48 ビュー (過去 30 日間)
Alexandros Katsikogiannis
Alexandros Katsikogiannis 2019 年 5 月 25 日
コメント済み: Stephen23 2019 年 5 月 27 日
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!

採用された回答

Stephen23
Stephen23 2019 年 5 月 25 日
編集済み: Stephen23 2019 年 5 月 25 日
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 件のコメント
Alexandros Katsikogiannis
Alexandros Katsikogiannis 2019 年 5 月 25 日
Nevermind, I managed to do it with a combination of "for" and "if" loop statements. Thanks again!
Stephen23
Stephen23 2019 年 5 月 27 日
Rather than using a loop, use logical indexing, as I showed in my answer.

サインインしてコメントする。

その他の回答 (1 件)

KALYAN ACHARJYA
KALYAN ACHARJYA 2019 年 5 月 25 日
編集済み: KALYAN ACHARJYA 2019 年 5 月 25 日
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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by