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

1 回表示 (過去 30 日間)
Burcu Yilmaz
Burcu Yilmaz 2019 年 12 月 11 日
コメント済み: Burcu Yilmaz 2019 年 12 月 11 日
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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by