python - generalisation between vector and matrix, matrix and tensor with numpy ndarray -
i found interesting thing when comparing matlab , 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 handle input may both ndarray shape (n,) , ndarray shape (n, m).
e.g.
def my_summation(x): """ x : ndarray each column of x observation. """ # solution ndarray shape (n,) # if x.ndim == 1: # x = x.reshape((-1, 1)) num_of_sample = x.shape[1] sum = np.zeros(x.shape[0]) in range(num_of_sample): sum = sum + x[:, i] return sum = np.array([[1, 2], [3, 4]]) b = np.array([1, 2]) print my_summation(a) print my_summation(b)
my solution forcing ndarray shape (n,) shape (n, 1).
the summation used example. want find elegant way handle possibility of matrix 1 observation(vector) , matrix more 1 observation using ndarray.
does have better solutions?
i learned numpy.atleast_2d
python control toolbox. don't need for-loop summation, rather use numpy.sum
.
import numpy np def my_summation(x): """ x : ndarray each column of x observation. """ # solution ndarray shape (n,) # if x.ndim == 1: # x = x.reshape((-1, 1)) x = np.atleast_2d(x) return np.sum(x, axis=1) = np.array([[1, 2], [3, 4]]) b = np.array([1, 2]) print my_summation(a) print my_summation(b)
gives
[3 7] [3]
Comments
Post a Comment