Removing all zeros in rows
11 次查看(过去 30 天)
显示 更早的评论
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 个评论
Image Analyst
2016-4-7
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).
采纳的回答
Matthew Eicholtz
2016-4-7
It is not possible to have a (full) array with varying number of rows. MATLAB wants to store something in those empty spots.
But, I think sparse arrays may do the trick for you...try this:
B = sparse(A);
Then to get the elements for a given column, use:
nonzero(B(:,4)) %nonzero elements for the 4th column, for instance
0 个评论
更多回答(1 个)
Azzi Abdelmalek
2016-4-7
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 个评论
Azzi Abdelmalek
2016-4-7
编辑:Azzi Abdelmalek
2016-4-7
Ok, what is the problem with it since you have just 5 columns?
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!