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)
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);

Answers (2)

Star Strider
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
Jason Logston
Jason Logston on 29 Sep 2015
Well I have it running now just by setting t = 1, but the answer I am getting is not what I am looking for. I am getting the answer for t if you were just to solve the equation for t. I think the problem is that my x is not updating each time the equation is ran. I kept what I had and added x = P(t) as the last line in my while loop, seems to be a reasonable number. Thank you for the advice though.
Image Analyst
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
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);

Tags

Community Treasure Hunt

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

Start Hunting!