MATLAB Answers

abdel m
0

How to use result in each iteration in a for loop and then use it in next loop?

Asked by abdel m
on 12 Jun 2019
Latest activity Answered by Prasanth Sikakollu on 12 Jun 2019
how can i use the result of the first iteration in other For loop?

  3 Comments

What do you mean by the other For loop - nested for loop or next iteration or anything else??
If you can send me the code you wrote, it would be helpful in understanding your problem.
i have two loops like this:
in the first loop i calculate x (for example) and in the second i calculate y, but in each iteration x depends on y.
for i=1:10
x=.....;
% here i will get the result fo i=1 but i must simultanously use it in the second loop
end
%second loop
for i=1:10
y=....;
end
You can merge both the loops and use the result in the same iteration
for i=1:10
x = 10*i; % This is the value generated
y = x + 1; % Using generated value x to evaluate y
end

Sign in to comment.

2 Answers

Answer by KSSV
on 12 Jun 2019

for i = 1:10
a = rand+rand ; % this is the result in first loop
for j = 1:3
b = a+rand ; % result of first loop used in second loop
end
end

  0 Comments

Sign in to comment.


Answer by Prasanth Sikakollu on 12 Jun 2019

Merge both the loops and use the generated result in the same loop.
for i=1:10
x = 10*i; % This is the value generated. Expression on the RHS is a random one
y = x + 1; % Using generated value x to evaluate y
end
Hope this helps

  0 Comments

Sign in to comment.