How to use end result for the next iteration

1 visualización (últimos 30 días)
Zahid Iqbal Rana
Zahid Iqbal Rana el 27 de Dic. de 2014
Comentada: Zahid Iqbal Rana el 28 de Dic. de 2014
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

Respuestas (2)

Image Analyst
Image Analyst el 27 de Dic. de 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 comentarios
Zahid Iqbal Rana
Zahid Iqbal Rana el 27 de Dic. de 2014
See now please and help me if you can.
Image Analyst
Image Analyst el 27 de Dic. de 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.

Iniciar sesión para comentar.


Roger Stafford
Roger Stafford el 27 de Dic. de 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.)
  1 comentario
Zahid Iqbal Rana
Zahid Iqbal Rana el 28 de Dic. de 2014
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.

Iniciar sesión para comentar.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by