我觉得应该有一个简单的解决方案,但我找不到:
我有具有相同维度 n*n
的稀疏矩阵 A
B
。我想创建矩阵 C
,它复制 A
中的值,其中 B
不为零。
这是我的方法:
[r,c,v] = find(B);
% now I'd like to create an array of values using indices r and c,
% but this doesn't work (wrong syntax)
v2 = A(r,c);
% This won't work either
idx = find(B); % linear indexing, too high-dimensional
v2 = A(idx);
% and create C
C = sparse(r,c,v2,n,n);
这里有更多的细节:
- 我的矩阵非常大,因此解决方案需要高效。不幸的是,
C(B~=0) = B(B~=0);
不会这样做。 - 线性索引也不起作用,因为矩阵太大(
矩阵太大,无法返回线性索引。
)。
真的没有办法使用二维索引吗?
感谢您的帮助!
最佳答案
我认为 C = A .* (B~=0);
应该可以。在两个稀疏矩阵的逐项乘法中只会访问非零值,因此速度很快。
关于MATLAB 使用行和列索引向量访问稀疏矩阵中的多个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17173913/