Finding the first zero element in a row and fill the entire row with the last non zero element

1 回表示 (過去 30 日間)
I have an m*n matrix which has only zeros and natural numbers. If there is a zero in a row, all the remaining elements after the first zero are also zeros. I would like to replace all zero elements with the last non zero element in the row. I am looking for the fastest way to do it in Matlab. Is there anyway without a loop? if not, what is the best way? Thanks.
For example:
A = [1 3 1 0 0 0 0;
1 4 2 1 3 4 1;
2 3 1 2 3 3 0];
% and I would like to have
B = [1 3 1 1 1 1 1;
1 4 2 1 3 4 1;
2 3 1 2 3 3 3];

採用された回答

Stephen23
Stephen23 2016 年 4 月 1 日
編集済み: Stephen23 2016 年 4 月 1 日
>> A = [1,3,1,0,0,0,0;1,4,2,1,3,4,1;2,3,1,2,3,3,0]
A =
1 3 1 0 0 0 0
1 4 2 1 3 4 1
2 3 1 2 3 3 0
>> A(:,2:end) = A(:,2:end) - cumsum(diff(A,1,2).*(A(:,2:end)==0),2)
A =
1 3 1 1 1 1 1
1 4 2 1 3 4 1
2 3 1 2 3 3 3
  1 件のコメント
MHN
MHN 2016 年 4 月 1 日
Wow, the way that you use cumsum and diff is very interesting! Could you please explain the logic behind it ?

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

その他の回答 (1 件)

MHN
MHN 2016 年 4 月 1 日
編集済み: MHN 2016 年 4 月 1 日
It is my fastest way so far. Adding one column of zero at the end, finding the minimum of each row (which would be the first zero), and using a loop. Is there any way to use "find" in the similar manner? since we can set to find the first element (specially from the end) instead of minimum which will go through all the row and that must be faster.
temp = A;
temp(:,end+1) = 0;
[~, Ind] = min(temp, [],2 );
for i = 1:length(Ind)
temp(i,Ind(i):end) = temp(i,Ind(i)-1);
end
B = temp(:,1:end-1);

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by