how to fill with the last non empty value across each column

3 visualizaciones (últimos 30 días)
Qian cao
Qian cao el 30 de Oct. de 2015
Comentada: Qian cao el 1 de Nov. de 2015
Hi all, how can I fill the cells in each row with the last non empty or non zero value please? For example : the matrix is [0 9 7 0 0 ; 0 0 0 6 0;0 2 0 0 0; 8 0 4 2 0]; The result shows b=[09700;09760;02760;82420]. Any help is welcomed. Thank you very much.

Respuesta aceptada

Stephen23
Stephen23 el 30 de Oct. de 2015
Editada: Stephen23 el 30 de Oct. de 2015
A = [0 9 7 0 0 ; 0 0 0 6 0;0 2 0 0 0; 8 0 4 2 0]
B = A;
for k = 2:size(B,1)
idx = B(k,:)==0;
B(k,idx) = B(k-1,idx);
end
Produces this output:
>> A
A =
0 9 7 0 0
0 0 0 6 0
0 2 0 0 0
8 0 4 2 0
>> B
B =
0 9 7 0 0
0 9 7 6 0
0 2 7 6 0
8 2 4 2 0
  3 comentarios
Stephen23
Stephen23 el 30 de Oct. de 2015
Editada: Stephen23 el 30 de Oct. de 2015
Run this new code afterwards
idy = true;
for k2 = k:-1:1
idy = idy & A(k2,:)==0;
B(k,idy) = 0;
end
to get this:
>> B
B =
0 9 7 0 0
0 9 7 6 0
0 2 7 6 0
8 0 4 2 0

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

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

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by