How to use if statements with arrays?

24 views (last 30 days)
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
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
M Talha Rehman on 14 Dec 2021
What is the role of this function here " i = 1:4" in the above program?

Sign in to comment.

Accepted Answer

madhan ravi
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
Bruna Araújo
Bruna Araújo on 7 Dec 2018
When I changed the variable T to
T = [298.15;293.15;408;600] ;
The problem started again, the loop is only providing me results from condition 2.
I changed the T(i)<500 to T(i)<500.00 but it didn't make any difference.
madhan ravi
madhan ravi on 7 Dec 2018
nah , it's giving the right values

Sign in to comment.

More Answers (1)

Jos (10584)
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!