Removing all zeros in rows
Show older comments
Hi,
Doing
A(~any(A,2),:)=[];
just deletes the rows that have all zeros in it.
This is what A originally looks like
5 0 0 0
0 4 0 0
0 0 3 0
0 0 0 0
0 0 0 2
0 0 0 1
0 7 0 0
3 0 0 0
1 0 0 0
0 0 0 3
My actual matrix has 5 columns and 10,000 rows. There could be anywhere from all zeros to no zeros in a row.
I would like to see this:
5 4 3 2
3 7 _ 1
1
Sorry, the _ is just to symbolize that nothing is there.
Notice that each column could have a different amount of rows. So basically what I want is anywhere there is a zero for it to be gone and the rest of the rows shift up in that column. I'm dealing with a lot of data sets so writing a loop just is not the best thing for me.
Thanks!
3 Comments
Azzi Abdelmalek
on 7 Apr 2016
Can you post the exact result for the example you posted?
Azzi Abdelmalek
on 7 Apr 2016
And explain what nothing means? You result is a matrix or a cell array?
Image Analyst
on 7 Apr 2016
You're worried about a loop but not a cell array? Do you know how much overhead a cell array takes? And you're worried about a tiny 50,000 loop iterations which will happen in less than the blink of an eye? And you'd have to use a cell array to have nulls for some elements. Tell us why you think you need to remove zeros. Chances are you don't, and we could show you why and a better way if we just knew the big picture (whole context).
Accepted Answer
More Answers (1)
Azzi Abdelmalek
on 7 Apr 2016
Maybe you want this
A=[5 0 0 0
0 4 0 0
0 0 3 0
0 0 0 0
0 0 0 2
0 0 0 1
0 7 0 0
3 0 0 0
1 0 0 0
0 0 0 3]
c1=nonzeros(A(:,1))
n=numel(c1)
c2=nonzeros(A(:,2))
c2=[c2;nan(n-numel(c2),1)]
c3=nonzeros(A(:,3))
c3=[c3;nan(n-numel(c3),1)]
c4=nonzeros(A(:,4))
c4=[c4;nan(n-numel(c4),1)]
out=[c1 c2 c3 c4]
2 Comments
Josh Heiner
on 7 Apr 2016
Azzi Abdelmalek
on 7 Apr 2016
Edited: Azzi Abdelmalek
on 7 Apr 2016
Ok, what is the problem with it since you have just 5 columns?
Categories
Find more on Performance and Memory 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!