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

 採用された回答

Stephen23
Stephen23 2018 年 3 月 5 日
編集済み: Stephen23 2018 年 3 月 5 日

2 投票

>> 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 件のコメント

Steven Niggebrugge
Steven Niggebrugge 2018 年 3 月 5 日
brilliant! thanks
Steven Niggebrugge
Steven Niggebrugge 2018 年 3 月 5 日
Could you help me with implementing this for a matrix? i.e. for M = [3 4;0 2;0 0;5 0] which should result in M_adj = [3 4; 3 2; 3 2;5 2]
thanks!
Steven Niggebrugge
Steven Niggebrugge 2018 年 3 月 5 日
have to come up with a solution if a value in first row is 0, in that case we need to override this with 1 in the idx matrix...otherwise M(idx) gives error message. 0 in first row also needs to be carried forward until a non-zero value appears.
Guillaume
Guillaume 2018 年 3 月 5 日
編集済み: Guillaume 2018 年 3 月 5 日
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 2019 年 6 月 21 日
編集済み: Arturo Camacho Lozano 2019 年 6 月 21 日
Stephen's solution is very clever. Thanks!

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File Exchange で Loops and Conditional Statements についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by