简体   繁体   English

快速设置稀疏矩阵的多个值

[英]Fast way to set many values of sparse matrix

I have a sparse 5018x5018 matrix in MATLAB, which has about 100k values set to 1 (ie, about 99.6% empty). 我在MATLAB中有一个稀疏的5018x5018矩阵,它有大约100k的值设置为1(即大约99.6%为空)。

I'm trying to flip roughly 5% of those zeros to ones (ie, about 1.25m entries). 我试图将这些零中的大约5%翻转为1(即大约1.25m条目)。 I have the x and y indices in the matrix I want to flip. 我想要翻转的矩阵中有x和y索引。

Here is what I have done: 这是我做的:

sizeMat=size(network);
idxToReplace=sub2ind(sizeMat,x_idx, y_idx);
network(idxToReplace) = 1;

This is incredibly slow, in particular the last line. 这非常慢,尤其是最后一行。 Is there any way to make this operation run noticeably faster, preferably without using mex files? 有没有办法让这个操作运行得更快,最好不使用mex文件?

This should be faster: 这应该更快:

idxToReplace=sparse(x_idx,y_idx,ones(size(x_idx),size(matrix,1),size(matrix,2)); % Create a sparse with ones at locations
network=network+idxToReplace; % Add the two matrices

I think your solution is very slow because you create a 1.26e6 logical array with your points and then store them in the sparse matrix. 我认为你的解决方案非常慢,因为你用你的点创建了一个1.26e6逻辑数组,然后将它们存储在稀疏矩阵中。 In my solution, you only create a sparse matrix and just sum the two. 在我的解决方案中,您只创建一个稀疏矩阵并将两者相加。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM