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!