필터 지우기
필터 지우기

How do I exclude zeros from a matrix?

조회 수: 1 (최근 30일)
cfjunior
cfjunior 2013년 4월 29일
How do I exclude zeros from a matrix and create a new matrix? For example:
A = [1 2 0 3 0 4 5 0; 7 0 0 0 2 3 4 1] and I want
A = [1 2 3 4 5 0 0 0; 7 2 3 4 1 0 0 0]
?
  댓글 수: 1
cfjunior
cfjunior 2013년 4월 29일
Actualy I want to move all zeros to the end of each column

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

채택된 답변

Andrei Bobrov
Andrei Bobrov 2013년 4월 29일
편집: Andrei Bobrov 2013년 4월 29일
s = size(A);
A1 = zeros(s);
for j1 = 1:s(1)
A1(j1,1:nnz(A(j1,:))) = nonzeros(A(j1,:));
end
other variant:
At = A.';
i1 = sum(At~=0);
s = size(At);
A1 = zeros(size(At));
A1(sub2ind(s,i1,1:s(2))) = 1;
out = zeros(s);
out(flipud(cumsum(flipud(A1)))>0) = At(At ~= 0);
out = out.';

추가 답변 (1개)

Zhang lu
Zhang lu 2013년 4월 29일
You just show an simple matrix , which has the same zeros in each row. So,if you matirx is this case, the code as first one. else, you can try the second code.
clear all
clc
A =[ 1 2 0 3 0 4 5 0
7 0 0 0 2 3 4 1];
A=A';
New_A=reshape(A(A~=0),[],size(A,2))';
New_A(:,size(A,1))=0
clear all
clc
A =[ 1 2 0 3 0 4 5 0
7 0 0 0 2 3 4 1
1 5 6 5 5 0 0 3];
[m,n]=size(A);
for i=1:m
B=A(i,A(i,:)~=0);
New_A(i,1:length(B))=B;
end
New_A(i,n)=0

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by