Info
This question is closed. Reopen it to edit or answer.
Having trouble figuring out how to write a loop, can someone tell me how I can fix my code?
1 view (last 30 days)
Show older comments
I am trying to determine the time (t) when P(t) will be zero. intially t should be zero, and then go up 1 every time it runs.
x = 10e10;
u = 10e6;
v = 0.04;
t = 0;
P(t) = (x - u * ( 1 + v * t ));
while( P(t) > 0.000000001)
t = t+1;
P(t) = (x - u * ( 1 + v * t ));
end
disp (t);
2 Comments
per isakson
on 29 Sep 2015
Edited: per isakson
on 29 Sep 2015
Matlab index is one-based. Replace
t = 0;
by
t = 1;
Answers (2)
Star Strider
on 29 Sep 2015
Being lazy, I would use the fzero function:
P = @(t) (x - u * ( 1 + v * t ));
tz = fzero(P, 1)
2 Comments
Image Analyst
on 29 Sep 2015
Did you see my answer? It uses your while loop, like you wanted, and gives the same answer for t that you'd get by solving the equation: t = 249975, which is also the same as what Star's answer gives. What answer were you expecting?
Image Analyst
on 29 Sep 2015
Try this - make an anonymous function.
x = 10e10;
u = 10e6;
v = 0.04;
t = 0;
P = @(t) (x - u * ( 1 + v * t ));
maxNumIterations = (x/u-1)/v+1;
while (P(t) > 0) && (t <= maxNumIterations)
fprintf('P(%d) = %f\n', t, P(t));
t = t + 1;
end
fprintf('P(%d) = %f\n', t, P(t));
plot(0:t, P(0:t), 'b-', 'LineWidth', 2);
grid on;
message = sprintf('t = %d\nP(t) = %f', t, P(t));
helpdlg(message);
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!