Conditional Loop not executing properly

So I am trying to build a loop that will calculate a problem for me. The problem being that for a range of certain x values I need a coefficient to equal something and at the other x values, the coefficient will equal something else. My loop won't run at all if I add an else statement(basically a catch-all to return an error) and when I take it off it won't calculate the values for the first condition.
t=[0:1:6];
r=zeros(1,length(t));
r(1)=0;
for i=1:(length(t))
if t(i) < 2
b(i)=1;
elseif t(i) >= 2
b(i)=150;
x(i)=(b(i)*r(i))+20;
r(i+1)=r(i)+x(i);
fprintf('%.4f %.2f\n',t(i),r(i))
end
end
I don't know what I'm doing wrong

4 Kommentare

jonas
jonas am 7 Okt. 2018
Bearbeitet: jonas am 7 Okt. 2018
Me neither, it's running fine for me.
b =
1 1 150 150 150 150 150
I am wondering if one end is misplaced though
t=[0:1:6];
r=zeros(1,length(t));
r(1)=0;
for i=1:(length(t))
if t(i) < 2
b(i)=1;
elseif t(i) >= 2
b(i)=150;
end
x(i)=(b(i)*r(i))+20;
r(i+1)=r(i)+x(i);
fprintf('%.4f %.2f\n',t(i),r(i))
end
Walter Roberson
Walter Roberson am 7 Okt. 2018
You probably want the end after the assignment of 150. MATLAB does not use spacing to indicate control level
Star Strider
Star Strider am 7 Okt. 2018
Your code runs without error for me.
Please also post the version that does not run.
What result do you want from it? (Please provide an example.)
Gwen Plato
Gwen Plato am 7 Okt. 2018
Your suggestion worked Walter, thanks

Antworten (0)

Diese Frage ist geschlossen.

Tags

Gefragt:

am 7 Okt. 2018

Geschlossen:

am 20 Aug. 2021

Community Treasure Hunt

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

Start Hunting!

Translated by