Borrar filtros
Borrar filtros

Help on for loop

2 visualizaciones (últimos 30 días)
Mark
Mark el 12 de Mzo. de 2013
I have an R vector and a U vector. The R vector contains mostly zeros but has a couple of values. The U vector is a shorter length than the R vector and contains no zeros. I want to make a U_final vector which has the values of the U vector at the same locations where the R vector values are non-zero. My attempted code is below. It iterates through fine, but the end result is the last value in U in all locations where R is non-zero rather than all values of U in the appropriate non-zero locations of R. I'm using U = [0.0137;0.0081] and R = [0;0;0;72;0;90]. I'd like the output to be U_final = [0;0;0;0.0137;0;0.0081]
for i = 1:length(R)
for j = 1:length(U)
if R(i,1) ~= 0
U_final(i,1) = U(j,1)
else U_final(i,1) == 0
end
end
end
  1 comentario
Walter Roberson
Walter Roberson el 12 de Mzo. de 2013
Note that U_final(i,1) == 0 is a comparison statement, not an assignment.

Iniciar sesión para comentar.

Respuesta aceptada

Teja Muppirala
Teja Muppirala el 12 de Mzo. de 2013
No need to iterate. MATLAB makes this simple with logical indexing.
U = [0.0137;0.0081];
R = [0;0;0;72;0;90];
U_final = R;
U_final(R~=0) = U
But the number of nonzeros in R needs to be equal to the length of U.
  1 comentario
Mark
Mark el 12 de Mzo. de 2013
Thanks Teja. I now see it as a quick replacement of the nonzero elements. No need to overcomplicate things is apparently the lesson for the day. ;) cheers!

Iniciar sesión para comentar.

Más respuestas (1)

Youssef  Khmou
Youssef Khmou el 12 de Mzo. de 2013
Editada: Youssef Khmou el 12 de Mzo. de 2013
hi try this , BUT the number of non zeros in R must be the same as the length of U:
R=zeros(100,1);
R(2:4:55)=rand; % R contains some values ( 14 elements !)
U=rand(14,1); % U is Shorter than R and contains non zeros vals
index=find(R~=0); %locations where R has non zeros .
U_final=zeros(size(R)); % this is optional
U_final(index)=U;

Categorías

Más información sobre Logical en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by