Effacer les filtres
Effacer les filtres

Replace values in matrix by first non-zero value in previous row

6 vues (au cours des 30 derniers jours)
Hi, how can i replace zero values in a matrix by the first occurring non-zero value in that matrix if you would loop backwards in each column? I.e. how can i carry forward a value as long as its next value in the same column is zero (without looping through each value in the matrix!)
Example: m_start = [3;0;0;4;0;5] replace_non_zero_values (m_start) = [3;3;3;4;4;5]
Hope you can help, thanks very much! Steven

Réponse acceptée

Stephen23
Stephen23 le 5 Mar 2018
Modifié(e) : Stephen23 le 5 Mar 2018
>> M = [3;0;0;4;0;5];
>> idx = M~=0;
>> tmp = M(idx);
>> tmp(cumsum(idx))
ans =
3
3
3
4
4
5
Note this assumes that the first value is nonzero. You will need to think of how to deal with leading zeros!
  5 commentaires
Guillaume
Guillaume le 5 Mar 2018
Modifié(e) : Guillaume le 5 Mar 2018
idx = M(:) ~= 0
tmp = M(idx);
reshape(tmp(cumsum(idx)), size(M))
As with the original answer, this will go badly wrong if any column starts with a 0.
Arturo Camacho Lozano
Arturo Camacho Lozano le 21 Juin 2019
Modifié(e) : Arturo Camacho Lozano le 21 Juin 2019
Stephen's solution is very clever. Thanks!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Numerical Integration and Differentiation dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by