Files
ailearning/docs/da/036.md
2020-10-19 21:08:55 +08:00

141 lines
1.2 KiB
Markdown
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 对角线
这里,使用与之前不同的导入方法:
In [1]:
```py
import numpy as np
```
使用numpy中的函数前需要加上 `np.`
In [2]:
```py
a = np.array([11,21,31,12,22,32,13,23,33])
a.shape = 3,3
a
```
Out[2]:
```py
array([[11, 21, 31],
[12, 22, 32],
[13, 23, 33]])
```
查看它的对角线元素:
In [3]:
```py
a.diagonal()
```
Out[3]:
```py
array([11, 22, 33])
```
可以使用偏移来查看它的次对角线,正数表示右移,负数表示左移:
In [4]:
```py
a.diagonal(offset=1)
```
Out[4]:
```py
array([21, 32])
```
In [5]:
```py
a.diagonal(offset=-1)
```
Out[5]:
```py
array([12, 23])
```
可以使用花式索引来得到对角线:
In [6]:
```py
i = [0,1,2]
a[i, i]
```
Out[6]:
```py
array([11, 22, 33])
```
可以更新对角线的值:
In [7]:
```py
a[i, i] = 2
a
```
Out[7]:
```py
array([[ 2, 21, 31],
[12, 2, 32],
[13, 23, 2]])
```
修改次对角线的值:
In [8]:
```py
i = np.array([0,1])
a[i, i + 1] = 1
a
```
Out[8]:
```py
array([[ 2, 1, 31],
[12, 2, 1],
[13, 23, 2]])
```
In [9]:
```py
a[i + 1, i] = -1
a
```
Out[9]:
```py
array([[ 2, 1, 31],
[-1, 2, 1],
[13, -1, 2]])
```