升序排序,但最后保留零 [英] Sort in ascending order, but keep zeros at last
问题描述
假设我有以下形式的矩阵A
.
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.
我知道我可以用inf
替换所有零,对其进行排序,然后再次将inf
替换为零,如
I know I can subsitute all zeros with inf
, sort it, and replace the inf
s 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?
我想要什么:
A =
3 1 6
35 9 0
0 32 0
0 0 0
谢谢!
关于Eitan的答案的开销存在一个问题.结果如下(平均,以及预热后):
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.
推荐答案
如果可以保证零仅位于每一列的底部,则可以执行以下操作:
If you can guarantee that the zeros are only at the bottom of each column, you can do:
A(A ~= 0) = nonzeros(sort(A));
这篇关于升序排序,但最后保留零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!