MATLAB Answers

How to remove zeros from an array?

조회 수: 4,502(최근 30일)
Elvis Somers
Elvis Somers 2017년 3월 20일
편집: Patrick Benz 2021년 10월 6일 11:18
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?

채택된 답변

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?
  댓글 수: 6
Patrick Benz
Patrick Benz 2021년 10월 6일 8:13
Das scheint zumindest schon einmal für die Reihen zu funktionieren, welche nur 0 Elemente enthalten.
Bei den gemischten Reihen funktioniert es aber offensichtlich nicht, da nur die Reihen von A behalten werden, welche keine 0 enthalten.
Wenn ich den Code so auf meine Matrix anwende, bekomme ich einen 0 x 20 double als Ergebnis.
Wäre es einfacher, wenn ich wüsste, wie viele 0 pro Reihe in der Matrix enthalten sind?
Edit:
Auch wenn es sicherlich nicht das schnellste oder eleganteste Ergebnis ist, habe ich es mit geschachtelten Schleifen geschafft.
Elementset_Nodes = 22762 x 21 double
Node_Coord = 7765 x 1 double
r=1;
[LIA, LOCB]=ismember(Elementset_Nodes(:,2:end),Node_Coord(:,1));
for i=1:length(LOCB)
X=0;
X=find(LOCB(i,:));
if sum(X)~=0
for j=1:length(X)
new_Mat(r,1)=Elementset_Nodes(i,1);
new_Mat(r,j+1)=LOCB(i,X(j));
end
else
new_Mat(r,:)=0;
new_Mat(r,:)=[];
end
[r, c]=find(new_Mat);
r=max(r)+1;
end
Elementset_Nodes=horzcat(Elementset_Nodes(:,1),new_Mat);

댓글을 달려면 로그인하십시오.

Community Treasure Hunt

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

Start Hunting!

Translated by