How to use end result for the next iteration
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (2)
Image Analyst
am 27 Dez. 2014
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 Kommentare
Image Analyst
am 27 Dez. 2014
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
am 27 Dez. 2014
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.)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!