Replacing row in matrix with previous row depending on condition

2 visualizzazioni (ultimi 30 giorni)
Say I have a matrix:
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:
The matrix consists of 1 million rows, so I'm looking for the fastest method.

Risposta accettata

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

Accedi per commentare.

Più risposte (1)

David Hill
David Hill il 19 Giu 2020
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


Scopri di più su Characters and Strings in Help Center e File Exchange




Community Treasure Hunt

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

Start Hunting!

Translated by