1
votes

I have to switch between MATLAB and NumPy (Python 3.x) . What always causes problems for me, is the way vectors are used in NumPy. In MATLAB a vector is more or less nothing else than a 1xn or nx1 matrix. To provide an example:

b=np.array([0,2])

is a (2,) array and in fact it is not useful for any matrix operation because in that case I have to do something like b.reshape(2,1) before. At almost any time I have to reshape the vectors/arrays returned by functions. Can someone tell me why NumPy arrays are not treated like column or row vectors by default? And because I have got to do it so often … is reshape the best way to do it?

1
I usually use b[:, None] if I need a (n,1) array. numpy usually treats a (n,) array as (1,n), that is it adds new dims at the start if needed. Matlab expends dims at the other end.hpaulj

1 Answers

2
votes

IMHO, Numpy's array-based-syntax is much more flexible and convenient than Matlab's linear-algebra-based syntax. In most cases, numpy code will be more clean and easy to write/follow. The only few exceptions arise when you are performing simple linear algebra operations where Matlab's syntax is slightly more efficient.

Note that you do not need to reshape numpy arrays in order to mimic matlab's operations in most cases. For example A.dot(b) or A@b (python 3) where A is a matrix (2-dimensional numpy.array) is essentially the same as A*b in Matlab. Give yourself some time to familiarize with numpy and you will see that it is Matlab that "forces" you to overuse/abuse the reshape function, not numpy.