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

조회 수: 4(최근 30일)
Burcu Yilmaz 11 Dec 2019
댓글: Burcu Yilmaz 11 Dec 2019
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?

로그인 to comment.

### 채택된 답변

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

#### 댓글 수: 1

Burcu Yilmaz 11 Dec 2019
Thank you so much!

로그인 to comment.

### 추가 답변(0개)

이 질문에 답변하려면 로그인을(를) 수행하십시오.

Translated by