How to use if statements with arrays?
Show older comments
I am trying to use an if statement with an array,
T = 300:300:1800
for i = 1:4
%condition 1
if T(i) <= 500
A = 28.98641;
B = 1.853978;
y = A*T+B*T^2/2
else
%condition 2
A = 19.50583;
B = 19.88705;
y = A*T+B*T^2/2
end
end
I want the result to take y from "condition 1" if T is lower or equal to 500 and from "condition 2" if T is grater than 500.
However, the outcome always gets the result from condition 2.
2 Comments
Stephen23
on 7 Dec 2018
"How to use if statements with arrays?"
Usually the best answer is "don't". Just use logical indexing, it is simpler.
M Talha Rehman
on 14 Dec 2021
What is the role of this function here " i = 1:4" in the above program?
Accepted Answer
More Answers (1)
Jos (10584)
on 7 Dec 2018
You need to assign the i-th calculation the i-th element in y in the two conditions
y(i) = ...
To speed things up, especially for large loops, you can pre-allocate y before the loop
y = nan(1,4) % assuming the loop is 4
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!