Running an inner loop multiple times.
4 views (last 30 days)
Show older comments
Hi all,
I'm a novice with Matlab. I have the following code that works, however I want to run the loop multiple times (number_of_runs), (montecarlo sim).
I'm assuming i need another loop, but i'm having no luck, i.e. exceeding numbers of arrays or generating more columns.
For example if the nth_failure = 10, i want the output of 10 columns for x and t, with the number_of_runs being a defined number of rows. Averaging each column.
for i = 2:nth_failure
p(i) = rand;
r_t_T = (p(i) .* exp(-(v(i-1)./n).^b));
x(i) = ((n .* (-log(r_t_T)).^(1./b))-v(i-1));
t(i) = t(i-1) + x(i);
v(i)= qf*(v(i-1)+x(i));
end
any help appreciated.
Cheers
2 Comments
KSSV
on 11 Oct 2021
Are you getting any error with the above code? What error? We don't know the dimensions of other varbales to help you.
Accepted Answer
KSSV
on 11 Oct 2021
Edited: KSSV
on 11 Oct 2021
You may proceed something like shown. Check your code and values once, t is coming as inf. This should give you some idea.
number_of_runs = 60;
q = 0.3;
b = [1.3];
n = [35.42822637];
nth_failure = 10;
p = zeros(number_of_runs,nth_failure);
x = zeros(number_of_runs,nth_failure);
v = zeros(number_of_runs,nth_failure);
t = zeros(number_of_runs,nth_failure);
r_t_T= zeros(number_of_runs,nth_failure);
qf = 1-q;
v0 = 0;
p(1) = rand();
x(:,1) = n .* (-log(p(number_of_runs,1))).^(1./b);
t(:,1) = x(:,1);
v(1,1) = v0 + qf * x(1) ;
for i = 1:number_of_runs
for j = 2:nth_failure
p(i,j) = rand;
r_t_T = (p(i,j) .* exp(-(v(i,j-1)./n).^b));
x(i,j) = ((n .* (-log(r_t_T)).^(1./b))-v(i,j-1));
t(i,j) = t(i,j-1) + x(i,j);
v(i,j)= qf*(v(i,j-1)+x(i,j));
end
end
The second loop can be removed and vectorised. Once you get this, try for that.
More Answers (1)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!