MATLAB如何使用矢量化形式填充稀疏矩阵的各个条目? [英] MATLAB How to fill individual entries of a sparse matrix using vectorised form?

查看:223
本文介绍了MATLAB如何使用矢量化形式填充稀疏矩阵的各个条目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个稀疏矩阵,我需要用特定的值填充某些条目,我现在正在使用for循环,但是我知道它不是正确的实现方式,所以我想知道是否有可能将其向量化循环吗?

I have a sparse matrix and I need to fill certain entries with a specific value, I am using a for loop right now but I know its not the correct way to do it so I was wondering if its possible to vectorise this for loop?

K = sparse(N);
for i=vectorofrandomintegers
    K(i,i) = 1;
end

如果我正常地将其矢量化:

If I vectorise it normally as so:

K(A,A) = 1;

然后它填充由A表示的每一行中的所有条目,而我想要单独的条目(即K(1,1) = 1K(6,6)=1).

then it fills all the entries in each row denoted by A whereas I want individual entries (i.e. K(1,1) = 1 or K(6,6)=1).

此外,条目不是沿对角线相邻的,因此我无法将单位矩阵放入其中.

Also, the entries are not diagonally adjacent so I can't plop the identity matrix into it.

推荐答案

如果要使用向量化方法,则需要获取要设置的线性索引.问题是,如果将稀疏矩阵定义为K = sparse(N),然后线性索引到K,它将仅在一个方向上而不是沿着行和列同时扩展其大小.因此,您需要向MATLAB指定您是 希望使用这种稀疏来存储2D数组.因此,它将是-

If you are going to use a vectorized method, you would need to get the linear indices to be set. The issue is that if you define your sparse matrix as K = sparse(N) and then linearly index into K, it would extend the size of it in one direction only and not along both row and column. Thus, you need to specify to MATLAB that you are looking to use this sparse to store a 2D array. Thus, it would be -

K = sparse(N,N);

使用 sub2ind 并进行设置-

ind1 = sub2ind([N N],vectorofrandomintegers,vectorofrandomintegers);
K(ind1) = 1;

这篇关于MATLAB如何使用矢量化形式填充稀疏矩阵的各个条目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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