作为更大函数的一部分,我正在编写一些代码来生成包含输入向量/矩阵"x"的每列的平均值的向量/矩阵(取决于输入).这些值存储在与输入矢量相同形状的矢量/矩阵中.
我对它在1-D和矩阵阵列上工作的初步解决方案非常(!)凌乱:
# '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))
Run Code Online (Sandbox Code Playgroud)
来自MATLAB背景,这就是它在MATLAB中的样子:
[R,C] = size(x);
for d = 1:C,
xmean(:,d) = zeros(R,1) + mean(x(:,d));
end
Run Code Online (Sandbox Code Playgroud)
这适用于矢量和矩阵,没有错误.
我的问题是,如何在没有(丑陋的)try/except块的情况下使我的python代码能够处理向量和矩阵格式的输入?
谢谢!