Matlab:使用column \row索引对分配给矩阵 [英] Matlab: assign to matrix with column\row index pairs
问题描述
可能重复:
如何更改矩阵中多个点的值?
我有一个矩阵 A
和三个长度相同的向量, r
,保存要分配的行的索引, c
,保存要分配的列的索引,以及 v
包含要分配的实际值。
I have a matrix A
and three vectors of the same length, r
, holding the indexes of the rows to assign to, c
, holding the indexes of the columns to assign to, and v
containing the actual values to assign.
我想得到的是 A(r(i),c(i))== v(i)
适用于所有 i
。但是这样做
What I want to get is A(r(i),c(i))==v(i)
for all i
. But doing
A(r,c)=v;
由于matlab将其解释为选择<$ c $的每个可能组合,因此无法产生正确的结果c> r 和 c
并为其赋值,例如
Doesn't yield the correct result as matlab interprets it as choosing every possible combination of r
and c
and assigning values to it, for instance
n=5;
A=zeros(n);
r=1:n;
c=1:n;
A(r,c)=1;
产生一个矩阵,我希望得到单位矩阵,因为我想要<$ c每个 i
的$ c> A(r(i),c(i))== 1 ,这只是对角线上的元素应该受到影响。
Yields a matrix of ones, where I would like to get the identity matrix since I want A(r(i),c(i))==1
for each i
, that is only elements on the diagonal should be affected.
如果没有 for
循环,我怎样才能达到预期效果?
How can I achieve the desired result, without a for
loop?
推荐答案
好的,我找到了答案 - 需要使用线性索引,即将column \row对转换为单个索引:
OK, I've found the answer - one needs to use linear indexing, that is convert the column\row pairs into a single index:
idx = sub2ind(size(A), r,c);
A(idx)=v;
这篇关于Matlab:使用column \row索引对分配给矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!