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
0 件のコメント
回答 (2 件)
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
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
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.)
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!