How can I repeat this simulation 1000 times

U1= 13.5;
U2= 9;
dt= 0.01; %time step
MAXT= 0.5;%maximum time (s)
a= 1.2; % threshold
x1(1)=0.5*a;
x2(1)=0.5*a;
for i= 1:MAXT/dt;
x1(i+1) = x1(i) + dt*(U1-U2)+ sqrt(dt)*randn- sqrt(dt)*randn;
end

 Accepted Answer

U1= 13.5;
U2= 9;
dt= 0.01; %time step
MAXT= 0.5;%maximum time (s)
a= 1.2; % threshold
x1(1)=0.5*a;
x2(1)=0.5*a;
inerations_nos=1;
while inerations_nos<1001
for i= 1:MAXT/dt;
x1(i+1) = x1(i) + dt*(U1-U2)+ sqrt(dt)*randn- sqrt(dt)*randn;
end
inerations_nos=inerations_nos+1;
end
or
for j=1:1000
%code
end

8 Comments

Thanks. I'm new to MATLAB. I tried the code you have written but it didn't give me an array. My aim is to get a 1000 x 51 array/vector(?). Also,I tried the following for the second method but didn't get an answer. Please, what am I doing wrong?
for j=1:1000
for i= 1:MAXT/dt;
x1(i+1) = x1(i) + dt*(U1-U2)+ sqrt(dt)*randn- sqrt(dt)*randn;
end
end
Which array you are looking for? Is it x1?
Torsten
Torsten on 4 Feb 2019
Edited: Torsten on 4 Feb 2019
x1 = zeros(1000,MAXT/dt+1);
for j = 1:1000
x1(j,1) = 0.5*a;
for i = 1:MAXT/dt;
x1(j,i+1) = x1(j,i) + dt*(U1-U2)+ sqrt(dt)*randn- sqrt(dt)*randn;
end
end
Thank you very much. I think this works. Please if you don't mind, could you explain the code to me?I'm a beginner and trying to learn MATLAB language.
%cretes zero matrix with size 1000xMAXT/dt+1
x1 = zeros(1000,MAXT/dt+1);
%for loop upto 1000 iterations
for j = 1:1000
%x1(j,1) here j represents row number and 11 represents column
x1(j,1) = 0.5*a;
%for loop 1 to MAXT/dt
for i = 1:MAXT/dt;
%randn-random number
x1(j,i+1)=x1(j,i) + dt*(U1-U2)+ sqrt(dt)*randn- sqrt(dt)*randn;
end
end
Start from beginner learn Matlab
Keep learning!
Good Wishes!
Read comments below:
x1 = zeros(1000,MAXT/dt+1); % creates 1000 rows, (MAXT/dt+1) columns zero matrix
for j = 1:1000 % for loop for 1000 times (that means each row will be filled with some number inside this loop)
x1(j,1) = 0.5*a; % (here, jth row 1st column element is filled with 0.5*a - you already know j is from 1 to 1000)
for i = 1:MAXT/dt; % for loop for filling other columns. MAXT/dt number of columns you have to fill now, because you already filled the first column above outer loop
x1(j,i+1) = x1(j,i) + dt*(U1-U2)+ sqrt(dt)*randn- sqrt(dt)*randn; % fills jth row, and the other columns (starts with 2nd to MAXT/dt column) with calculated random number
end
end
% in the end you will get x1 -> 1000 column MAXT/dt+1 rows filled.
% Note: X(j,i) means X's 2D matrix and jth is row number, ith is column number
% X(2,3) -> gives you 2nd row, 3rd column element
Thank you very much. This has helped a lot!

Sign in to comment.

More Answers (0)

Categories

Find more on Get Started with MATLAB in Help Center and File Exchange

Products

Release

R2018b

Asked:

on 4 Feb 2019

Commented:

on 4 Feb 2019

Community Treasure Hunt

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

Start Hunting!