Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort in ascending order, but keep zeros at last

Tags:

sorting

matlab

Suppose I have a matrix A, on the following form.

A =
    35     1     6
     3    32     0
     0     9     0
     0     0     0

I want to sort it in ascending order, but keep the zeros at last.

I know I can subsitute all zeros with inf, sort it, and replace the infs with zeros again, as proposed in this question.

I would think there was a simpler way. At least since my zeros are already in the bottom rows. Can I do this in a single line?

What I want:

A =
     3     1     6
     35    9     0
     0     32    0
     0     0     0

Thanks!

UPDATE

There was a question regarding the overhead of Eitan's answer. Here are the results (averaged, and after warm up):

B =  kron(A,ceil(rand(2000)*1000));  % 8000x6000 matrix
C = B;

%% Eitan's solution:
t1 = tic; B(B ~= 0) = nonzeros(sort(B)); toc(t1)
Elapsed time is  1.768782 seconds.

%% From question text:
B = C;
t1 = tic; B(B==0)=Inf; B = sort(B); B(B==Inf)=0; toc(t1) 
Elapsed time is 1.938374 seconds.

%% evading's solution (in the comments):
B = C;
t1 = tic; for i = 1:size(B,2)  index = B(:,i) ~= 0; B(index, i) = sort(B(index, i)); end
toc(t1)
Elapsed time is 1.954454 seconds.

%% Shai's solution (in the comments):
B = C;
t1 = tic; sel = B==0; B(sel)=inf;B=sort(B);B(sel)=0; toc(t1)
Elapsed time is 1.880054 seconds.
like image 629
Stewie Griffin Avatar asked Jun 02 '13 11:06

Stewie Griffin


People also ask

How do I sort by 0 in Excel?

To sort values ignore zeros, you need to create a helper column and apply a formula. 3. Click Sort, and the values are sorted from smallest to largest ignoring zeros. You can remove the helper column after sorting.

Does ascending order Mean A to Z or Z to A?

In general terms, Ascending means smallest to largest, 0 to 9, and/or A to Z and Descending means largest to smallest, 9 to 0, and/or Z to A.

Does ascending sort A to Z?

When arranging them in ascending order they are arranged from A to Z – or beginning to end. When it comes to dates, ascending order would mean that the oldest ones come first and the most recent ones last.


1 Answers

If you can guarantee that the zeros are only at the bottom of each column, you can do:

A(A ~= 0) = nonzeros(sort(A));
like image 124
Eitan T Avatar answered Sep 29 '22 20:09

Eitan T