如何在对角线上分配值? [英] How to assign values on the diagonal?
问题描述
假设我有一个NxN矩阵A,一个由数字1:N的子集和一个值K组成的索引向量V,我想这样做:
Suppose I have an NxN matrix A, an index vector V consisting of a subset of the numbers 1:N, and a value K, and I want to do this:
for i = V
A(i,i) = K
end
有没有一种方法可以在向量化语句中做到这一点?
Is there a way to do this in one statement w/ vectorization?
例如A(某物)= K
语句A(V,V) = K
将不起作用,它分配了非对角线元素,这不是我想要的.例如:
The statement A(V,V) = K
will not work, it assigns off-diagonal elements, and this is not what I want. e.g.:
>> A = zeros(5);
>> V = [1 3 4];
>> A(V,V) = 1
A =
1 0 1 1 0
0 0 0 0 0
1 0 1 1 0
1 0 1 1 0
0 0 0 0 0
推荐答案
我通常使用 EYE :
A = magic(4)
A(logical(eye(size(A)))) = 99
A =
99 2 3 13
5 99 10 8
9 7 99 12
4 14 15 99
或者,您也可以只创建线性索引列表,因为从一个对角线元素到下一个对角线元素需要nRows+1
个步骤:
Alternatively, you can just create the list of linear indices, since from one diagonal element to the next, it takes nRows+1
steps:
[nRows,nCols] = size(A);
A(1:(nRows+1):nRows*nCols) = 101
A =
101 2 3 13
5 101 10 8
9 7 101 12
4 14 15 101
如果只想访问对角线元素的子集,则需要创建一个对角线索引列表:
If you only want to access a subset of diagonal elements, you need to create a list of diagonal indices:
subsetIdx = [1 3];
diagonalIdx = (subsetIdx-1) * (nRows + 1) + 1;
A(diagonalIdx) = 203
A =
203 2 3 13
5 101 10 8
9 7 203 12
4 14 15 101
或者,您可以使用diag
创建逻辑索引数组(仅适用于正方形数组)
Alternatively, you can create a logical index array using diag
(works only for square arrays)
diagonalIdx = false(nRows,1);
diagonalIdx(subsetIdx) = true;
A(diag(diagonalIdx)) = -1
A =
-1 2 3 13
5 101 10 8
9 7 -1 12
4 14 15 101
这篇关于如何在对角线上分配值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!