How to remove rows contain 0 in matrix
3 views (last 30 days)
Show older comments
Assume matrix A as follows:
A = [1 1 2 2 3 3
10 10 7 10 9 5
5 45 4 15 1 10
1 50 3 30 5 65
6 55 1 0 8 90
2 0 2 0 2 0
3 0 5 0 3 0
4 0 6 0 4 0
7 0 8 0 6 0
8 0 9 0 7 0
9 0 10 0 10 0
];
I want to remove rows contain 0 and make new matrix B. In the matrix B, the first column is unique ID which are repeated based on matrix A (first row).
B = [1 10 10
1 5 45
1 1 50
1 6 55
2 7 10
2 4 15
2 3 30
2 3 3
2 9 5
2 1 10
2 5 65
2 8 90
];
0 Comments
Answers (3)
dpb
on 8 Mar 2017
The first part seems pretty easy, but I've no klew how you actually got B from what's left...in fact, there are several elements retained that don't show up at all if the rows containing zero are removed--the 8,90 values for just one case.
>> A(all(A,2),:)
ans =
1 1 2 2 3 3
10 10 7 10 9 5
5 45 4 15 1 10
1 50 3 30 5 65
>>
3 Comments
dpb
on 12 Mar 2017
OK, had some time to try to deduce how the output was produced...other than there's an error in the original in that the first row [3 3] values were included initially that was most confusing as well as the indices didn't include 1:3 but 1:2, I think what you're looking for is (given the last A as starting point)--
>> [As,iA]=sort(A(:,2:4)); % Sort columns exclusive of index
>> nR=sum(As>0); % find how many are in each column excluding zeros
>> ix=find(As>0); % indices nonzeros locations in column-major order
>> B=[cell2mat(arrayfun(@(n,c) repmat(c,n,1),nR.',[1:length(nR)].','uniform',0)) iA(ix) As(ix)]
B =
1 10 10
1 5 45
1 1 50
1 6 55
2 7 10
2 4 15
2 3 30
3 9 5
3 1 10
3 5 65
3 8 90
>>
0 Comments
Akira Agata
on 15 Mar 2017
Maybe I could understand what you want. To clarify, I wrote the code in step-by-step manner. I hope this matches to what you want to do.
A = [1 50 0 10
2 0 0 0
3 0 30 0
4 0 15 0
5 45 0 65
6 55 0 0
7 0 10 0
8 0 0 90
9 0 0 5
10 10 0 0
];
idx = A(:,2) == 0;
B1 = [sortrows(A(~idx,[1 2]),2); sortrows(A(idx,[1 2]),1)];
idx = A(:,3) == 0;
B2 = [sortrows(A(~idx,[1 3]),2); sortrows(A(idx,[1 3]),1)];
idx = A(:,4) == 0;
B3 = [sortrows(A(~idx,[1 4]),2); sortrows(A(idx,[1 4]),1)];
% Now, [B1 B2 B3] is the matrix B in Alex's post on 8 Mar 2017 at 22:01.
% Extract the target columns
C = [B1(:,1) B2(:,1) B3(:,1)];
0 Comments
See Also
Categories
Find more on Multidimensional Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!