如何为 MATLAB 矩阵的对角线赋值?
假设我有一个 NxN 矩阵 A、一个由数字 1:N 的子集组成的索引向量 V 和一个值 K,我想这样做:
for i = V
A(i,i) = K
end
有没有一种方法可以在一个带有向量化的语句中做到这一点?
例如 A(something) = K
语句 A(V,V) = K
不起作用,它分配非对角线元素,这不是我想要的。例如:
>> 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
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?
e.g. A(something) = 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
我通常使用 EYE :
或者,您可以只创建列表线性索引,因为从一个对角元素到下一个,需要 nRows+1 步:
如果您只想访问对角元素的子集,则需要创建一个对角索引列表:
或者,您可以使用
diag
创建逻辑索引数组(仅适用于方形数组)I usually use EYE for that:
Alternatively, you can just create the list of linear indices, since from one diagonal element to the next, it takes
nRows+1
steps:If you only want to access a subset of diagonal elements, you need to create a list of diagonal indices:
Alternatively, you can create a logical index array using
diag
(works only for square arrays)更一般地说:
这是基于矩阵可以作为一维数组(向量)访问的事实,其中 2 个索引 (m,n) 被线性映射 m*N+n 替换。
and more general:
This is based on the fact that matrices can be accessed as one-dimensional arrays (vectors), where the 2 indices (m,n) are replaced by a linear mapping m*N+n.
我将使用 sub2ind 并将对角线索引作为 x 和 y 参数传递:
I'd use
sub2ind
and pass the diagonal indices as both x and y parameters:假设 K 是值。该命令
可能会快一点,
经过的时间是 0.517575 秒。
经过的时间是 0.353408 秒。
但它会消耗更多的内存。
Suppose K is the value. The command
may be a bit faster
Elapsed time is 0.517575 seconds.
Elapsed time is 0.353408 seconds.
But it consumes more memory.
我在有限差分代码中使用这个小内联函数。
通过更改函数范围,可以轻松修改它以在对角线的子范围上工作。
I use this small inline function in finite difference code.
It can be easily modified to work on a sub-range of the diagonal by changing the function range.