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

3 Ansichten (letzte 30 Tage)
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.

Akzeptierte Antwort

Alex Mcaulley
Alex Mcaulley am 11 Dez. 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')

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by