假设我有一个矩阵A
,在下面的表格中。
A =
35 1 6
3 32 0
0 9 0
0 0 0
我想按升序排序,但最后保留零。
我知道我可以使用inf
替换所有零,对其进行排序,并再次将inf
替换为零,如this question中所提议的那样。
我认为有一种更简单的方法。至少因为我的零已经在底行。我可以一行完成吗?
我想要的是什么:
A =
3 1 6
35 9 0
0 32 0
0 0 0
谢谢!
关于Eitan答案的开销存在疑问。以下是结果(平均值和热身后):
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.
答案 0 :(得分:8)
如果您可以保证零只位于每列的底部,则可以执行以下操作:
A(A ~= 0) = nonzeros(sort(A));