Repalce zero element by the number before it ?
Mostrar comentarios más antiguos
If I have array called N,
N = [2 0 7 0 9 10 0 0 11 0 0 ];
I want to create new array M that have [2 2 7 7 9 10 10 10 11 11 11]
Here is other example
N=[ 0 1 4 5 6 7 0 10 0 0 0]
the one I would create is
M=[0 1 4 5 6 7 7 10 10 10 10].
I would replace each zero in array N by the number before it except the first zero.
Thank you in advance.
Respuesta aceptada
Más respuestas (2)
KSSV
el 17 de En. de 2019
N=[ 0 1 4 5 6 7 0 10 0 0 0] ;
M = N ;
idx = find(N==0) ; % get the indices of zeros
while ~isempty(idx)
idx(idx==1) = [] ; % remove the index if zero is at one
M(idx) = M(idx-1) ; % replace zeros with previous values
idx = find(M==0) ;
idx(idx==1) = [] ;
end
madhan ravi
el 17 de En. de 2019
Editada: madhan ravi
el 17 de En. de 2019
EDITED
N = [2 0 7 0 9 10 0 0 11 0 0 ];
M=N;
M(M==0)=NaN;
M=fillmissing(M,'nearest')
Gives:
M =
2 2 7 7 9 10 10 10 11 11 11
N=[ 0 1 4 5 6 7 0 10 0 0 0];
M=N;
M(M==0)=NaN;
M=fillmissing(M,'previous');
M(1)=0
Gives:
M =
0 1 4 5 6 7 7 10 10 10 10
5 comentarios
Willim
el 17 de En. de 2019
madhan ravi
el 17 de En. de 2019
Editada: madhan ravi
el 17 de En. de 2019
Change 'nearest' to 'previous' , see edited answer.
madhan ravi
el 17 de En. de 2019
If you find it helpful you can vote for it.
Willim
el 17 de En. de 2019
madhan ravi
el 17 de En. de 2019
Editada: madhan ravi
el 17 de En. de 2019
What? Did you see the first example in my answer?
Categorías
Más información sobre Matrix Indexing en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!