MATLAB Answers

How to remove zeros from an array?

2,877 ビュー (過去 30 日間)
Elvis Somers
Elvis Somers 2017 年 3 月 20 日
コメント済み: Farshad Bolouri 2020 年 11 月 8 日
I want to remove zeroes from an array. The array has exactly one zero per row. For example:
a = [1 4 0 3; 0 1 5 5; 1 0 8 1; 5 4 4 0; 0 1 5 2]
Should be turned into
a = [1 4 3; 1 5 5; 1 8 1; 5 4 4; 1 5 2]
I have tried using the command
a(a==0) = [];
However, this turns the 2000x50 array into an 1x98000 array instead of an 2000x49 array like I want it. Any ideas?

  0 件のコメント

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

採用された回答

Beder
Beder 2017 年 3 月 20 日
編集済み: MathWorks Support Team 2018 年 11 月 28 日
To remove a single zero from each row of a matrix and rebuild the new matrix of nonzero entries, try the following code:
a = [1 4 0 3; 0 1 5 5; 1 0 8 1; 5 4 4 0; 0 1 5 2]
v = nonzeros(a');
newmat = reshape(v,3,5)'

  1 件のコメント

Elvis Somers
Elvis Somers 2017 年 3 月 20 日
Thanks!

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

その他の回答 (1 件)

saber kazemi
saber kazemi 2018 年 12 月 12 日
If we do not know how much of the elements to submit after we remove the zero elements.
a = [is a big matrix]
v = nonzeros(a');
newmat = reshape(v,?,?)'
Any ideas?

  2 件のコメント

ytzhak goussha
ytzhak goussha 2018 年 12 月 16 日
I have been working on this problme for the some time now,
so far the solution that i have reached works better if you know for certain that the number of zeros in each row is the same, if not, then it must be converted to a cell class.
a=matrix %a big matrix with unknown number of zeroes
[sz1,sz2]=size(a);
new_sz2=zeros(1,sz1) %This array will hold the size of each row after removing zeros
for i=1:sz1
new_mat{i}= nonzeros(a(i,:));
new_row_sz(i)=size(new_mat{i},1)
end
if range(new_row_sz) == 0
new_mat=cell2mat(new_mat);
end
Farshad Bolouri
Farshad Bolouri 2020 年 11 月 8 日
This is how I have solved this problem:
Z = find(~a);
[x,~] = ind2sub(size(a),Z);
a(x,:) = [];
This worked for my application. Please me know if it also works for you. It is possible to tweek it for different applications.

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

Community Treasure Hunt

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

Start Hunting!

Translated by