将矩阵中的-1全部替换为math.inf
时间: 2024-02-23 11:01:19 浏览: 21
要将矩阵中的-1全部替换为`math.inf`,可以使用Python中的NumPy库和math库。以下是一个示例代码:
```python
import numpy as np
import math
# 创建一个3x3的矩阵
mat = np.array([[1, -1, 3],
[0, 4, -1],
[6, -1, 7]])
# 将矩阵中的-1替换为math.inf
mat[mat == -1] = math.inf
print(mat)
```
输出结果为:
```
[[ 1. inf 3.]
[ 0. 4. inf]
[ 6. inf 7.]]
```
在上述代码中,通过`mat == -1`创建了一个布尔类型的矩阵,表示原矩阵中哪些位置上的数值为-1。然后,通过`mat[mat == -1] = math.inf`将所有布尔矩阵中为True的位置的值替换为`math.inf`。
相关问题
将矩阵中的数值-1全部替换为数值math.inf
要将矩阵中的数值-1全部替换为math.inf,可以使用NumPy库中的np.where()函数。该函数可以根据条件选择要使用的值。你可以使用条件matrix == -1来选择要替换的数值,并使用np.inf来指定替换值。
以下是一个示例代码:
``` python
import numpy as np
import math
# 创建一个3x3的矩阵
matrix = np.array([[1, 2, -1],
[4, -1, 6],
[-1, 8, 9]])
# 使用np.where()函数根据条件替换数值
matrix = np.where(matrix == -1, math.inf, matrix)
# 打印替换后的矩阵
print(matrix)
```
输出结果为:
```
[[ 1. 2. inf]
[ 4. inf 6.]
[inf 8. 9.]]
```
在这个示例中,我们使用np.where()函数根据条件matrix == -1来选择要替换的数值,并使用math.inf来指定替换值。最终的矩阵中所有的-1都被替换为了math.inf。
matlab 构造矩阵[1,-1,1,-1......]
可以使用以下代码构造该矩阵:
n = 10; % 矩阵的大小
A = repmat([1,-1],1,n/2); % 重复生成 [1,-1] 序列
if mod(n,2) == 1 % 如果 n 是奇数,则加上最后一个元素 1
A(end+1) = 1;
end
A = reshape(A,n,[]); % 将向量转换为矩阵
disp(A); % 显示矩阵