假设我有一个矩阵A,在下面的表格中.
A =
35 1 6
3 32 0
0 9 0
0 0 0
Run Code Online (Sandbox Code Playgroud)
我想按升序排序,但最后保留零.
我知道我可以inf替换所有零,对它进行排序,并inf再次用零替换s,如本问题所述.
我认为有一种更简单的方法.至少因为我的零已经在底行.我可以一行完成吗?
我想要的是:
A =
3 1 6
35 9 0
0 32 0
0 0 0
Run Code Online (Sandbox Code Playgroud)
谢谢!
关于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.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
823 次 |
| 最近记录: |