removing 0 values from an array while maintaining an array

4 ビュー (過去 30 日間)
nnnnnew01
nnnnnew01 2022 年 3 月 30 日
回答済み: Voss 2022 年 3 月 30 日
i have used data(data == 0) = [] to remove the 0's however it shifts the remaining numbers into columns rather than keeping the array layout? wondering if there is a way to keep it in array format and remove 0 values.

回答 (1 件)

Voss
Voss 2022 年 3 月 30 日
If you know there are always the same number of zeros in each column, you can reshape after removing them:
% random matrix with one zero in each column:
M = rand(7,3);
M([7 9 18]) = 0
M = 7×3
0.0755 0.9933 0.5442 0.9886 0 0.9228 0.8358 0.5746 0.2469 0.2092 0.6053 0 0.6826 0.6172 0.6560 0.7813 0.7701 0.4630 0 0.4167 0.1692
n_zeros = 1; % one zero per column
M = reshape(M(M ~= 0),size(M)-[n_zeros 0])
M = 6×3
0.0755 0.9933 0.5442 0.9886 0.5746 0.9228 0.8358 0.6053 0.2469 0.2092 0.6172 0.6560 0.6826 0.7701 0.4630 0.7813 0.4167 0.1692

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by