How to use end result for the next iteration

1 次查看(过去 30 天)
Please help me how i can use end result of this code for the next iteration. The value of e at the end of 1st iteration must be used as equal to b in d=2.*b.^2 for the next iterations
The code is:-
clear all;
clc;
a=rand(5,1);
c=2.*a.^2;
[minValC, minIndC]=min(c)
for i=1:5
z=rand(5,1);
p=2.*z.^2;
[minValp, minIndp]=min(p)
b=rand(5,1);
d=2.*b.^2;
[minVald, minIndd]=min(d)
e=zeros(5,1);
for j=1:5
if p(j)<d(j)
e(j)=z(j);
else
e(j)=b(j);
end
end
e;
f=2.*e.^2;
[minValf, minIndf]=min(f)
end

回答(2 个)

Image Analyst
Image Analyst 2014-12-27
What you said is really confusing. The only thing I can figure for you "to use e=b for i=2" is to do this:
e(2) = b(2);
By the way, this loop
for i=1:5
if c(i)<d(i)
e(i)=a(i);
else
e(i)=b(i);
end
end
can be vectorized like
e=b;
logicalIndexes = c < d;
e(logicalIndexes) = a(logicalIndexes);
though for a for loop of only 5 elements you won't notice any speed difference.
  2 个评论
Image Analyst
Image Analyst 2014-12-27
Please indicate exactly where "the end result of the code" is available.
There are two "for" loops. When you say "at the end of 1st iteration" do you mean during the first "i" iteration and at the end of the first iteration of the "j" loop? In other words, at the end of the j loop (just before the "end", not after the j loop) where j = 1, and i = 1.

请先登录,再进行评论。


Roger Stafford
Roger Stafford 2014-12-27
In my opinion, there is a lot of wasted computation in your code, Zahid. For example, the inequality p(j)<d(j) is equivalent to z(j)<b(j), so it is unnecessary to do the computations p=2.*z.^2 and d=2.*b.^2 until exiting from the loops. Similarly, computations of the type
[minValf, minIndf]=min(f)
can all be postponed until exiting the loops.
Here is code I claim is probably equivalent to what I am guessing you are trying to get:
e = rand(5,1);
for n = 1:N % N is the desired number of iterations
e = min([e,rand(5,1)],[],2);
end
f = 2*e.^2;
[minValf, minIndf]=min(f);
(This assumes that you don't need to save b, d, p, and z since they are all being continually overwritten, and similarly it is assumed you didn't actually need a and c, since they are never used in the remaining code.)
  1 个评论
Zahid Iqbal Rana
Zahid Iqbal Rana 2014-12-28
Thank you for your answer.
I got your point, but I want to make sure that the main code is not that I write above. Its just an example.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by