文章目录(Table of Contents)
Add 1 to diagonal elements of a matrix(矩阵的对角元素加1)
问题
问题链接:https://mathematica.stackexchange.com/questions/156063/add-1-to-diagonal-elements-of-a-matrix
原文
I have a list of lists of numbers, for example:
{{1,1,1,1},{1,1,1,1},{1,1,1,1},{1,1,1,1}}
The length of the list is the same length of each sublist. What I want to achieve is to add plus 1 to the diagonal elements without using For. Given the list above as an input, I need a result like this:
{{2,1,1,1},{1,2,1,1},{1,1,2,1},{1,1,1,2}}
Thank you.
翻译
我有一列包含许多有数字的列表的列表,例如:
{{1,1,1,1},{1,1,1,1},{1,1,1,1},{1,1,1,1}}
列表的长度和列表中每个子列表的长度相等。我想做的是给对角线的元素加1,并且不使用For循环。以上面给出的列表为例,我需要的输出如下:
{{2,1,1,1},{1,2,1,1},{1,1,2,1},{1,1,1,2}}
谢谢。
高票回答
原文
By popular demand:
list + IdentityMatrix@Length@list
I'm a big fan of IdentityMatrix -- I try to use it whenever possible.
翻译
受人气的需要:
list + IdentityMatrix@Length@list
运行结果:
![Add 1 to diagonal elements of a matrix(矩阵的对角元素加1)–[4]](https://img.mathpretty.com/snipaste_20170926_113052.png?imageView2/0/q/75|watermark/2/text/5YWz5rOo5YWs5LyX5Y-377ya5paH6Im65pWw5a2m5ZCb/font/5b6u6L2v6ZuF6buR/fontsize/540/fill/IzAwMDAwMA==/dissolve/100/gravity/SouthEast/dx/10/dy/10|imageslim)
我十分喜欢使用IdentityMatrix--每当有需要我一定会使用他。
- 微信公众号
- 关注微信公众号
-
- QQ群
- 我们的QQ群号
-

![Creating a third list from two given lists(通过以给出的两个列表创建第三个列表)--[5]](https://img.mathpretty.com/20210911_162117_jmo0vhq.jpg)
![在使用Grid中的Frame->All时,如何不要在空白的单元格加边框--[3]](https://img.mathpretty.com/20210911_162056_tt49p1t.jpg)
![omit a pairing of numbers from two data ranges in a table(从table产生的两组数中忽略一些数据范围)--[2]](https://img.mathpretty.com/20210911_162047_y47j0gu.jpg)
![Geolocate multiple IP addresses(获取大量IP地址的地理位置)--[1]](https://img.mathpretty.com/20210911_161401_9q0dovo.jpg)

评论