Am I doing this right?
显示 更早的评论
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.
采纳的回答
更多回答(1 个)
Image Analyst
2012-9-30
编辑:Image Analyst
2012-9-30
Nice try, but not quite right. You can try again but get rid of the "t = 0:0.001:100" line. Plus I have no idea what you're doing with ctr.
Anyway, there's a more MATLABish way of doing it:
h = input('input height of object (< 5):') ;
t = 0:0.001:100;
element_exceeds_h = find(5*sin(t) > h, 1, 'first')
time_that_happens = t(element_exceeds_h)
Note that 5*sint(t) is the height as a function of time, and T can be a whole vector - it does not need to be a single value. That's the benefit of MATLAB! element_exceeds_h is the element of your t array where the height exceeds the user's input. The value of t at that element is when it happens.
2 个评论
Nathan
2012-9-30
Image Analyst
2012-9-30
编辑:Image Analyst
2012-9-30
Close, you almost got it, but you need to keep track of time and the height separately in an array so you can plot them. Plus you also have the actual height at time t plus the desired height, so there are two heights, not just one.
clc;
clearvars;
desiredHeight = input('Input height of object:')
counter = 1;
t = 0;
while t >= 0;
t = t + 0.001
timeAxis(counter) = t;
height(counter) = t + 5*sin(t);
fprintf('\n\nHeight = %.2f at t = %.2f!\n', height(counter), t);
if height(counter) >= desiredHeight
fprintf('\n\nThe time for the object to reach a height of %.3f is %.3f seconds!\n', height(counter), t);
break;
end
counter = counter + 1;
end
plot(timeAxis, height, 'b-');
grid on;
counter
% Enlarge figure to full screen.
set(gcf, 'units','normalized','outerposition',[0 0 1 1]);
类别
在 帮助中心 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!