Sort in ascending order, but zeros are preserved

Suppose I have a matrix A , in 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 finally keep zeros.

I know that I can replace all zeros of inf , sort it, and replace inf zeros again, as suggested in this question .

I think there was an easier way. At least since my zeros are already in the bottom lines. Can I do this on one line?

What I want:

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

Thanks!

UPDATE

The question arose about Eitan's overhead. Here are the results (averaged and after warming up):

 B = kron(A,ceil(rand(2000)*1000)); % 8000x6000 matrix C = B; %% Eitan 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 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 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. 
+6
source share
1 answer

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

 A(A ~= 0) = nonzeros(sort(A)); 
+8
source

Source: https://habr.com/ru/post/946339/


All Articles