使用 Mathematica 更改矩阵的对角线
有没有一种优雅的方法将矩阵的对角线更改为新的值列表, 相当于 Band 和 SparseArray?
假设我有以下矩阵(见下文),
(mat = Array[Subscript[a, ##] &, {4, 4}]) // MatrixForm
并且我想将主对角线更改为以下以获得“新垫”(见下文)
newMainDiagList = Flatten@Array[Subscript[new, ##] &, {1, 4}]
我知道使用 ReplacePart 将主对角线更改为给定值很容易。例如:
ReplacePart[mat, {i_, i_} -> 0]
我也希望不局限于主对角线(就像 Band 不受 SparseArray 的限制一样)
(我目前使用的方法如下!)
(Normal@SparseArray[Band[{1, 1}] -> newMainDiagList] +
ReplacePart[mat, {i_, i_} -> 0]) // MatrixForm
(所需输出是“new mat” ')
Is there an elegant way to change the diagonals of a matrix to a new list of values, the
equivalent of Band with SparseArray?
Say I have the following matrix (see below)
(mat = Array[Subscript[a, ##] &, {4, 4}]) // MatrixForm
and I'd like to change the main diagonal to the following to get "new mat" (see below)
newMainDiagList = Flatten@Array[Subscript[new, ##] &, {1, 4}]
I know it is easy to change the main diagonal to a given value using ReplacePart. For example:
ReplacePart[mat, {i_, i_} -> 0]
I'd also like not to be restricted to the main diagonal (in the same way that Band is not so restricted with SparseArray)
(The method I use at the moment is the following!)
(Normal@SparseArray[Band[{1, 1}] -> newMainDiagList] +
ReplacePart[mat, {i_, i_} -> 0]) // MatrixForm
(Desired Output is 'new mat')
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
实际上,您根本不需要使用
Normal
。SparseArray
加上一个“普通”矩阵就得到了一个“普通”矩阵。初步检查,使用Band
是最灵活的方法,但有效(且灵活性稍差)的替代方法是:DiagonalMatrix
还接受第二个整数参数,该参数允许您指定newDiagList< 的对角线/code> 表示主对角线由 0 表示。
然而,最优雅的替代方案是更有效地使用
ReplacePart
:替换Rule
可以是RuleDelayed
,例如,它直接进行替换,无需中间步骤。
编辑:为了模仿
Band
的行为,我们还可以通过/;
。例如,替换主对角线正上方的对角线 (
Band[{1,2}]
),并且仅替换
4x4
中主对角线的最后两个元素> 矩阵 (Band[{3,3}]
)。但是,直接使用ReplacePart
要简单得多。Actually, you don't need to use
Normal
whatsoever. ASparseArray
plus a "normal" matrix gives you a "normal" matrix. UsingBand
is, on initial inspection, the most flexible approach, but an effective (and slightly less flexible) alternative is:DiagonalMatrix
also accepts a second integer parameter which allows you to specify which diagonal thatnewDiagList
represents with the main diagonal represented by 0.The most elegant alternative, however, is to use
ReplacePart
a little more effectively: the replacementRule
can be aRuleDelayed
, e.g.which does your replacement directly without the intermediate steps.
Edit: to mimic
Band
's behavior, we can also add conditions to the pattern via/;
. For instance,replaces the diagonal immediately above the main one (
Band[{1,2}]
), andwould only replace the last two elements of the main diagonal in a
4x4
matrix (Band[{3,3}]
). But, it is much simpler usingReplacePart
directly.