【发布时间】:2012-01-22 08:35:05
【问题描述】:
作为更大函数的一部分,我正在编写一些代码来生成一个向量/矩阵(取决于输入),其中包含输入向量/矩阵“x”的每一列的平均值。这些值存储在与输入向量形状相同的向量/矩阵中。
我的初步解决方案是在一维和矩阵数组上工作的非常(!)混乱:
# 'x' is of type array and can be a vector or matrix.
import scipy as sp
shp = sp.shape(x)
x_mean = sp.array(sp.zeros(sp.shape(x)))
try: # if input is a matrix
shp_range = range(shp[1])
for d in shp_range:
x_mean[:,d] = sp.mean(x[:,d])*sp.ones(sp.shape(z))
except IndexError: # error occurs if the input is a vector
z = sp.zeros((shp[0],))
x_mean = sp.mean(x)*sp.ones(sp.shape(z))
来自 MATLAB 背景,这就是它在 MATLAB 中的样子:
[R,C] = size(x);
for d = 1:C,
xmean(:,d) = zeros(R,1) + mean(x(:,d));
end
这适用于向量和矩阵,没有错误。
我的问题是,如何让我的 python 代码在没有(丑陋的)try/except 块的情况下同时处理向量和矩阵格式的输入?
谢谢!
【问题讨论】:
-
公平地说,matlab 根本没有一维数组。 matlab中的“一维”向量是二维的。
-
如果您打算使用 2D/1D 输出来计算标准,那么您不需要 2D 输出,并且可以通过广播在任何情况下使用 1D 数组。