MATLAB: Am I doing this right

beginnerwhile loop

I have to use the while loop to write a function that will ask for a given height of an object and return the time it takes for the object to reach that height given that h=t+5*sin(t), with a time increment of 0.001, and it has to output "The time for the object to reach a height of (h) is (answer) seconds" so far ive got this:
h= input('input height of object:')
ctr = 0; t = 0:0.001:100;
while t > 0;
t = t + 0.001
h = t + 5*sin(t);
ctr = t + 1;
end
h
ctr
this is my first programming class and i have zero experience could anyone tell me what im doing wrong? i don't know how to the output expression, but the code i have currently isnt correct.

Best Answer

Here is the output of running a modified version of your script:
input height of object:123
h =
123
x =
123.0039
ctr =
121.0200
t =
120.0200
where your modified script is
h = input('input height of object:');
ctr = 0;
t = 0;
x = -999; % to make sure to get into the loop
while x < h
t = t + 0.001;
x = t + 5*sin(t);
ctr = t + 1;
end
h
x
ctr
t
Note that
  • t is a scalar that is incremented by 0.001 in each loop.
'
--- In response to comments ---
This line, which I copied from Image Analysts comment and adapted, should do the trick
fprintf('\n\nThe time for the object to reach a height of %.3f is %.3f seconds!\n', x, t);
add it to the end of your script.
Some more comments:
  • programming well is difficult - IMO
  • there are at least two reasons why short variable names are often used: i) quicker to type and ii) not that long ago the cost of processing long names did matter. I have once changed names to squeeze a program into an "Apple II"
  • it is a good idea to use self explaining names
  • "while tentative_height < target_height" is easier to understand
  • ctr in the script could be removed
  • there are certainly more efficient ways to solve this equation
Related Question