How to use if statements with arrays?
24 views (last 30 days)
Show older comments
Bruna Araújo
on 7 Dec 2018
Commented: M Talha Rehman
on 14 Dec 2021
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
madhan ravi
on 7 Dec 2018
Edited: madhan ravi
on 7 Dec 2018
Note: The below can be achieved using logical indexing which is easier and less work to do.
T = 300:300:1800
y=zeros(1,4); % prellocate %% I suspect 4 should be numel(T)
for i = 1:4
%condition 1
if T(i) <= 500
A = 28.98641;
B = 1.853978;
y(i) = A*T(i)+B*T(i)^2/2; % use iterator as index -> (i)
else
%condition 2
A = 19.50583;
B = 19.88705;
y(i) = A*T(i)+B*T(i)^2/2;
end
end
4 Comments
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
0 Comments
See Also
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!