How do I save my values of x each time the loop goes round?

1 view (last 30 days)
This is my Matlab code. How do i change it so that each value of x is stored when the loop goes round? I'm trying to plot it and compare.
%IC
clear
x = 1;
time = 0;
dt = 0.1;
%for loop calculating x after 10 iterations
for n = 1:10;
k1 = 4*x+2*time-3;
k2 = 4*(x+(tchange*k1))+2*(time+dt)-3;
xnew = x+((dt/2)*(k1+k2))
x = xnew;
time = time + dt;
end
Help would be appreciated! :)

Accepted Answer

KSSV
KSSV on 21 Nov 2021
%IC
clear
x = 1;
time = 0;
dt = 0.1;
%for loop calculating x after 10 iterations
xx = zeros(10,1) ;
for n = 1:10;
k1 = 4*x+2*time-3;
k2 = 4*(x+(tchange*k1))+2*(time+dt)-3;
xnew = x+((dt/2)*(k1+k2))
x = xnew;
xx(n) = x ;
time = time + dt;
end
plot(xx)
  1 Comment
Dog Man
Dog Man on 21 Nov 2021
thank you! how do I plot this against time? (from 0 to 1 as there are 10 timesteps of 0.1)

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!