Storing while loop results in an array and plotting
3 ビュー (過去 30 日間)
古いコメントを表示
Hello, I have this simple code simulating free fall. The while loop works fine in the first case but i need to plot the results. I tried to put the y and v values in arrays but the results i get are wrong. How do i fix that?
clear, clc, close all, format long
% Initial values and constants
g = 10;
y = 100;
v = 0;
t = 0;
h = 0.1;
fprintf('\n\tt (sec)\t\ty (m)\t\tv (m/sec)\n')
fprintf('\n\t%.2f\t\t%.2f\t\t%.2f\n',t,y,v)
while y >= 0
y = y + h*v;
v = v - h*g;
t = t + h;
fprintf('\n\t%.2f\t\t%.2f\t\t%.2f\n',t,y,v)
end
subplot(2,1,1), plot(t,y), grid on
subplot(2,1,2), plot(t,v), grid on
% Alternative way - putting values in array
% Initial values and constants
g = 10;
i = 1;
y(i) = 100;
v(i) = 0;
t(i) = 0;
h = 0.1;
fprintf('\n\tt (sec)\t\ty (m)\t\tv (m/sec)\n')
fprintf('\n\t%.2f\t\t%.2f\t\t%.2f\n',t,y,v)
while y >= 0
y(i+1) = y(i) + h*v(i);
v(i+1) = v(i) - h*g;
t(i+1) = t(i) + h;
i = i + 1;
end
fprintf('\n\t%.2f\t\t%.2f\t\t%.2f\n',t,y,v)
subplot(2,1,1), plot(t,y), grid on
subplot(2,1,2), plot(t,v), grid on
0 件のコメント
採用された回答
Torsten
2025 年 1 月 5 日
編集済み: Torsten
2025 年 1 月 5 日
Why do you think the results you get from the second part of your code are wrong ?
g = 10;
y(1) = 100;
v(1) = 0;
t(1) = 0;
h = 0.1;
i = 1;
while y(i) >= 0
i = i + 1;
y(i) = y(i-1) + h*v(i-1);
v(i) = v(i-1) - h*g;
t(i) = t(i-1) + h;
fprintf('\n\t%.2f\t\t%.2f\t\t%.2f\n',t(i),y(i),v(i))
end
y = y(1:end-1);
v = v(1:end-1);
t = t(1:end-1);
subplot(2,1,1), plot(t,y), grid on
subplot(2,1,2), plot(t,v), grid on
1 件のコメント
Torsten
2025 年 1 月 5 日
編集済み: Torsten
2025 年 1 月 5 日
The below code linearly interpolates the time point t0 when y becomes 0 between the last two values for y, namely (t(end-1),y(end-1)) and (t(end),y(end)) with y(end-1) > 0 and y(end) <= 0:
g = 10;
y(1) = 100;
v(1) = 0;
t(1) = 0;
h = 0.1;
i = 1;
while y(i) > 0
i = i + 1;
y(i) = y(i-1) + h*v(i-1);
v(i) = v(i-1) - h*g;
t(i) = t(i-1) + h;
fprintf('\n\t%.2f\t\t%.2f\t\t%.2f\n',t(i),y(i),v(i))
end
t0 = (y(end)*t(end-1)-y(end-1)*t(end))/(y(end)-y(end-1));
t0 - t(end-1)
y(end) = 0;
v(end) = v(end-1) - (t0-t(end-1))*g;
t(end) = t0;
subplot(2,1,1), plot(t,y), grid on
subplot(2,1,2), plot(t,v), grid on
その他の回答 (0 件)
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!