假设我有一个矩阵A
,格式如下。
A =
35 1 6
3 32 0
0 9 0
0 0 0
我想按升序对其进行排序,但最后保留零。
我知道我可以用 替换所有零inf
,对其进行排序,然后inf
再次用零替换 s,正如在这个问题中提出的那样。
我认为有一个更简单的方法。至少因为我的零已经在底行了。我可以在一行中执行此操作吗?
我想要的是:
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.