2

I have a just a short question about the attributes shape and ndim. How can an array have more dimensions than two, but matrices are limited to a n x m shape? Would it not be necessary to have shapes with something like a m x n x o shape for a three-dimensional array?

Best regards

MDoe
  • 163
  • 1
  • 13

1 Answers1

0

I think you are confusing things here, np.array can have any number of dimensions and np.matrix only two, np.matrix is the specific case where ndim=2 and have special matrix operators. From NumPy documentation of np.matrix:

Note:
It is no longer recommended to use this class, even for linear algebra. 
Instead, use regular arrays. The class may be removed in the future.

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).

Also, notice this example so you can see the difference:

a = np.matrix([[2,2],[2,2]])
print(a**2)

This would return:

matrix([[8, 8],
        [8, 8]])

Because matrix "a" squared is that, but if you do the same thing with array:

a = np.array([[2,2],[2,2]])
print(a**2)

It will return:

array([[4, 4],
       [4, 4]])

Because it applied the square in all elements if you want the behaviour of np.matrix you would have to use np.dot

I think they will probably remove np.matrix in future versions because it doesn't add anything really useful other than bugging the mind of developers.

Bruno Mello
  • 4,448
  • 1
  • 9
  • 39