フィルターのクリア

How to delete nonzero values at the end of a matrix

1 回表示 (過去 30 日間)
Mister Finance
Mister Finance 2021 年 8 月 13 日
コメント済み: Mister Finance 2021 年 8 月 13 日
Assume I have the following array:
M = [1 1 1; 0 2 2; 3 3 0; 4 4 0; 0 5 0]
M = 5×3
1 1 1 0 2 2 3 3 0 4 4 0 0 5 0
How do I set all elements from the end of each row to the first nonzero value to NaN?
The result should look like this:
M = [1 1 1; 0 2 2; 3 3 NaN; 4 4 NaN; NaN 5 NaN]
M = 5×3
1 1 1 0 2 2 3 3 NaN 4 4 NaN NaN 5 NaN
It is important that only the zero values at the end are set equal to NaN and not all elements that are equal to zero.
Thank you!

採用された回答

Chunru
Chunru 2021 年 8 月 13 日
M = [1 1 1; 0 2 2; 3 3 0; 4 4 0; 0 5 0]
M = 5×3
1 1 1 0 2 2 3 3 0 4 4 0 0 5 0
for i=1:size(M, 2)
idx = find(M(:, i), 1, 'last');
M(idx+1:end, i) = nan;
end
M
M = 5×3
1 1 1 0 2 2 3 3 NaN 4 4 NaN NaN 5 NaN
%M = [1 1 1; 0 2 2; 3 3 NaN; 4 4 NaN; NaN 5 NaN]
  1 件のコメント
Mister Finance
Mister Finance 2021 年 8 月 13 日
Exactly what I was looking for. Thanks a lot!

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by