Replacing row in matrix with previous row depending on condition

3 ビュー (過去 30 日間)
Oliver Zacho
Oliver Zacho 2020 年 6 月 19 日
コメント済み: the cyclist 2020 年 6 月 19 日
Hi
Say I have a matrix:
A=[2,5,3;5,8,2;1,-2,5]
If a value in any of the rows are -2 the whole row should be replaced by the previous row.
So the result would be:
A=[2,5,3;5,8,2;5,8,1]
The matrix consists of 1 million rows, so I'm looking for the fastest method.

採用された回答

the cyclist
the cyclist 2020 年 6 月 19 日
Here is one way:
while any(A(:)==-2)
rowToReplace = find(any(A==-2,2));
A(rowToReplace,:) = A(rowToReplace-1,:);
end
This solution could probably made faster by using only logical indices, without the find command, but I felt lazy.
  2 件のコメント
Oliver Zacho
Oliver Zacho 2020 年 6 月 19 日
Thanks alot, this one does that job in a decent amount of time. Lovely. Have a splendid weekend.
the cyclist
the cyclist 2020 年 6 月 19 日
This is a little faster, in limited testing:
while any(A(:)==-2)
rowToReplace = any(A==-2,2);
A(rowToReplace,:) = A([rowToReplace(2:end); false],:);
end
The optimized version might depend on the pattern of -2's in the array.

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

その他の回答 (1 件)

David Hill
David Hill 2020 年 6 月 19 日
If you have consecutive rows containing -2, you will have to repeat until all the -2 rows have been replaced if that is your goal
[a,~]=find(A==-2);
a=unique(a);
A(a,:)=A(a-1,:);
  1 件のコメント
Oliver Zacho
Oliver Zacho 2020 年 6 月 19 日
Thanks alot! Have a nice weekend. :)

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

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by