How to run a loop with different values and plot the result?

3 views (last 30 days)
Hello,
Here is my code,
clear;
clc;
x=5;
Difference=[];
x_arr=[];
x_arr(1)=x;
dt=1;
for i=1:10/dt
xnew=x*dt;
x=xnew;
x_arr(i+1)=xnew;
end
Difference=abs(x_arr(1)-x_arr(end))
hold on
plot(dt,Difference,'o')
ylabel('Difference between initial and final x value')
xlabel('dt')
I have an initial x value and I put this x value into a loop, then I create an array. I calculate the difference between the initial x value and the final x value.
What i want to do is run this loop with different dt values (dt=1:1:10) and plot the result. For example,
dt=1 Difference=0
dt=2 Difference=155
dt=3 Difference=130
and so on.
I could do this with starting with my code ten times and use hold on before plotting. I am also including the figure that I got with starting the code by hand 10 times.
With this way I cannot increase the length of dt since I cannot start the code with1000 times.
I want to do this procedure with a loop. How can I do that?
Thank you in advance for your help.

Accepted Answer

Alex Mcaulley
Alex Mcaulley on 11 Dec 2019
Yo can do it with an external loop with dt:
for dt = 1:10
x=5;
x_arr=[];
x_arr(1)=x;
for i=1:10/dt
xnew=x*dt;
x=xnew;
x_arr(i+1)=xnew;
end
Difference=abs(x_arr(1)-x_arr(end))
hold on
plot(dt,Difference,'o')
end
hold off
ylabel('Difference between initial and final x value')
xlabel('dt')

More Answers (0)

Categories

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

Community Treasure Hunt

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

Start Hunting!