Storing while loop results in an array and plotting
Afficher commentaires plus anciens
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
Réponse acceptée
Plus de réponses (0)
Catégories
En savoir plus sur Structural Mechanics dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!


