我一直想知道这个问题很长一段时间,但找不到引用资料:Matlab 如何快速转置稀疏矩阵,假设它以 CSC(压缩稀疏列)格式存储?
还有 its documentation验证稀疏矩阵转置的效率:
To do this (accessing row by row), you can transpose the matrix, perform operations on the columns, and then retranspose the result … The time required to transpose the matrix is negligible.
跟进(根据@Mikhail 的建议修改):
我同意@Roger 和@Milhail 的观点,对于许多操作(例如 BLAS 或稀疏 BLAS 操作)的接口(interface)而言,设置一个标志就足够了。但在我看来,Matlab 确实进行了“实际”换位。例如,我有一个大小为 m*n=7984*12411 的稀疏矩阵 X,我想对每一列和每一行进行缩放:
% scaling each column
t = 0;
for i = 1 : 1000
A = X; t0 = tic;
A = bsxfun(@times, A, rand(1,n));
t = t + toc(t0);
end
t = 0.023636 秒
% scaling each row
t = 0;
for i = 1 : 1000
A = X; t0 = tic;
A = bsxfun(@times, A, rand(m,1));
t = t + toc(t0);
end
t = 138.3586 秒
% scaling each row by transposing X and transforming back
t = 0;
for i = 1 : 1000
A = X; t0 = tic;
A = A'; A = bsxfun(@times, A, rand(1,m)); A = A';
t = t + toc(t0);
end
t = 19.5433 秒
这个结果意味着逐列访问比逐行访问更快。这是有道理的,因为稀疏矩阵是逐列存储的。所以X'的列缩放速度快的唯一原因应该是X实际上是转置到X'而不是设置标志。
另外,如果每个稀疏矩阵都以CSC格式存储,那么简单地设置一个标志不能使X'为CSC格式。
有什么意见吗?提前致谢。
最佳答案
经过一周的探索,我对矩阵转置的内部机制的猜测是排序。
假设A
是一个稀疏矩阵,
[I, J, S] = find(A);
[sorted_I, idx] = sort(I);
J = J(idx);
S = S(idx);
B = sparse(J, sorted_I, S);
那么B
就是A
的转置。
上面的实现在我的机器上的效率大约是Matlab内置的transpose
的一半。考虑到 Matlab 的内置函数是多线程的,我的猜测可能是合理的。
关于matlab - Matlab如何转置稀疏矩阵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16721863/