在Python中初始化空矩阵 [英] Initialize empty matrix in Python
问题描述
我正在尝试在Python中转换MATLAB代码.我不知道如何在Python中初始化空矩阵.
I am trying to convert a MATLAB code in Python. I don't know how to initialize empty matrix in Python.
MATLAB代码:
demod4(1) = [];
我在Python中尝试过
I tried in Python
demod4[0] = array([])
但它给出了错误:
only length-1 arrays can be converted to Python scalars
推荐答案
If you are using numpy
arrays, you initialize to 0, by specifying the expected matrix size:
import numpy as np
d = np.zeros((2,3))
>>> d
[[ 0. 0. 0.]
[ 0. 0. 0.]]
这等同于MATLAB的:
This would be the equivalent of MATLAB 's:
d = zeros(2,3);
您还可以再次使用预期的尺寸/大小来初始化一个空数组
You can also initialize an empty array, again using the expected dimensions/size
d = np.empty((2,3))
如果您不使用 numpy,则最接近于 MATLAB 的 d = []
(即零大小矩阵)将使用一个空列表,然后使用
If you are not using numpy, the closest somewhat equivalent to MATLAB's d = []
(i.e., a zero-size matrix) would be using an empty list and then
附加值(用于填充向量)
append values (for filling a vector)
d = []
d.append(0)
d.append(1)
>>> d
[0, 1]
或附加列表(用于填充矩阵行或列):
or append lists (for filling a matrix row or column):
d = []
d.append(range(0,2))
d.append(range(2,4))
>>> d
[[0, 1], [2, 3]]
另见:
初始化一个 numpy 数组(SO)
这篇关于在Python中初始化空矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!