Repalce zero element by the number before it ?

1 回表示 (過去 30 日間)
Willim
Willim 2019 年 1 月 17 日
編集済み: madhan ravi 2019 年 1 月 17 日
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.

採用された回答

Image Analyst
Image Analyst 2019 年 1 月 17 日
Faraj:
Did you try the super obvious solution: a very simple "for" loop:
N = [2 0 7 0 9 10 0 0 11 0 0 ];
for k = 1 : length(N)
if N(k) == 0
N(k) = N(k-1);
end
end
Presumably so. Were you looking for some more compact vectorized or function-based solution instead?

その他の回答 (2 件)

KSSV
KSSV 2019 年 1 月 17 日
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
  2 件のコメント
Willim
Willim 2019 年 1 月 17 日
This works but for my entire code , my code keeps running until I pause the run and quit debugging. then type M in my command window then I got the right M.
could you please the algorithm code ?
KSSV
KSSV 2019 年 1 月 17 日
Give the value of N. Image Analyist solution is good....go ahead with that.

サインインしてコメントする。


madhan ravi
madhan ravi 2019 年 1 月 17 日
編集済み: madhan ravi 2019 年 1 月 17 日
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 件のコメント
Willim
Willim 2019 年 1 月 17 日
great it works but the thing is that the frist element could be 1 not 0 all the time
madhan ravi
madhan ravi 2019 年 1 月 17 日
編集済み: madhan ravi 2019 年 1 月 17 日
What? Did you see the first example in my answer?

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by