Removing all zeros in rows
8 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Josh Heiner
am 7 Apr. 2016
Bearbeitet: Azzi Abdelmalek
am 7 Apr. 2016
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 Kommentare
Azzi Abdelmalek
am 7 Apr. 2016
And explain what nothing means? You result is a matrix or a cell array?
Image Analyst
am 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).
Akzeptierte Antwort
Matthew Eicholtz
am 7 Apr. 2016
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 Kommentare
Weitere Antworten (1)
Azzi Abdelmalek
am 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 Kommentare
Azzi Abdelmalek
am 7 Apr. 2016
Bearbeitet: Azzi Abdelmalek
am 7 Apr. 2016
Ok, what is the problem with it since you have just 5 columns?
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!