Home > Net >  Keep Numpy Arrays 2D
Keep Numpy Arrays 2D

Time:12-16

I'm doing a lot of vector algebra and want to use numpy arrays to remove any need for loops and run faster.

What I've found is that if I have a matrix A of size [N,P] I constantly need to use np.array([A[:,0]).T to force A[:,0] to be a column vector of size (N,1)

Is there a way to keep the single row or column of a 2D array as a 2D array because it makes the following arithmetic sooo much easier. For example, I often have to multiply a column vector (from a matrix) with a row vector (also created from a matrix) to create a new matrix: eg

C = A[:,i] * B[j,:]

it'd be be great if I didn't have to keep using:

C = np.array([A[:,i]]).T * np.array([B[j,:]])

It really obfuscates the code - in MATLAB it'd simply be C = A[:,i] * B[j,:] which is easier to read and compare with the underlying mathematics, especially if there's a lot of terms like this in the same line, but unfortunately most of my colleagues don't have MATLAB licenses.

Note this isn't the only use case, so a specific function for this column x row operation isn't too helpful

CodePudding user response:

https://numpy.org/doc/stable/reference/generated/numpy.matrix.html

Returns a matrix from an array-like object, or from a string of data. A matrix is a specialized 2-D array that retains its 2-D nature through operations. It has certain special operators, such as * (matrix multiplication) and ** (matrix power).

I'm not sure how to re-implement it though, it's an interesting exercise.

As mentionned, matrix will be deprecated. But from np.array, you can specify the dimension with the argument ndim=2:

np.array([1, 2, 3], ndmin=2)

CodePudding user response:

You can keep the dimension in the following way (using @ for matrix multiplication)

C = A[:,[i]] @ B[[j],:]

Notice the brackets around i and j, otherwise C won't be a 2-dimensional matrix.

  • Related