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

1 次查看(过去 30 天)
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.

采纳的回答

Alex Mcaulley
Alex Mcaulley 2019-12-11
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')

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by