设置稀疏矩阵的许多值的快速方法 [英] Fast way to set many values of sparse matrix

查看:81
本文介绍了设置稀疏矩阵的许多值的快速方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在MATLAB中有一个稀疏的5018x5018矩阵,其中约有100k的值设置为1(即约有99.6%的空白).

I have a sparse 5018x5018 matrix in MATLAB, which has about 100k values set to 1 (i.e., about 99.6% empty).

我正在尝试将这些零的大约5%翻转为1(即大约125万个条目).我要翻转的矩阵中有x和y索引.

I'm trying to flip roughly 5% of those zeros to ones (i.e., about 1.25m entries). I have the x and y indices in the matrix I want to flip.

这是我所做的:

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

这非常慢,尤其是最后一行.有什么方法可以使此操作的运行速度明显加快,最好不要使用mex文件?

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?

推荐答案

这应该更快:

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

我认为您的解决方案非常慢,因为您用点创建了一个1.26e6逻辑数组,然后将它们存储在稀疏矩阵中.在我的解决方案中,您只需创建一个稀疏矩阵,然后将两者相加即可.

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. In my solution, you only create a sparse matrix and just sum the two.

这篇关于设置稀疏矩阵的许多值的快速方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆