Replace values in matrix by first non-zero value in previous row
5 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
Stephen23
2018-3-5
编辑:Stephen23
2018-3-5
>> 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 个评论
Arturo Camacho Lozano
2019-6-21
编辑:Arturo Camacho Lozano
2019-6-21
Stephen's solution is very clever. Thanks!
更多回答(0 个)
另请参阅
类别
在 Help Center 和 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!