I found an interesting thing when comparing MATLAB and numpy.
MATLAB:
x = [1, 2]
n = size(X, 2)
% n = 1
Python:
x = np.array([1, 2])
n = x.shape[1]
# error
The question is: how to handle input which may be both ndarray with shape (n,) and ndarray with shape (n, m).
e.g.
def my_summation(X):
"""
X : ndarray
each column of X is an observation.
"""
# my solution for ndarray shape (n,)
# if X.ndim == 1:
# X = X.reshape((-1, 1))
num_of_sample = X.shape[1]
sum = np.zeros(X.shape[0])
for i in range(num_of_sample):
sum = sum + X[:, i]
return sum
a = np.array([[1, 2], [3, 4]])
b = np.array([1, 2])
print my_summation(a)
print my_summation(b)
My solution is forcing ndarray shape (n,) to be shape (n, 1).
The summation is used as an example. What I want is to find an elegant way to handle the possibility of matrix with only one observation(vector) and matrix with more than one observation using ndarray.
Does anyone have better solutions?
axis=1and you wanted(n)to become(n,1), so for a 1D array case the output frommy_summation(X)would be same as inputX, right? - Divakar