0

Why the line3 raise valueError‘ matrix must be 2-dimensional’

import numpy as np
np.mat([[[1],[2]],[[10],[1,3]]])
np.mat([[[1],[2]],[[10],[1]]])

1

1 Answer 1

1

The reason why this code raises an error is because NumPy tries to determine the dimensionality of your input using nesting levels (nesting levels -> dimensions). If, at some level, some elements do not have the same length (i.e. they are incompatible), it will create the array using the deepest nesting it can, using the objects as the elements of the array.

For this reason:

np.mat([[[1],[2]],[[10],[1,3]]])

Will give you a matrix of objects (lists), while:

np.mat([[[1],[2]],[[10],[1]]])

would result in a 3D array of numbers which np.mat() does not want to squeeze into a matrix.

Also, please avoid using np.mat() in your code as it is deprecated. Use np.array() instead.

Incidentally, np.array() would work in both cases and it would give you a (2, 2, 1)-shaped array of int, which you could np.squeeze() into a matrix if you like. However, it would be better to start from nesting level of 2 if all you want is a matrix:

np.array([[1, 2], [10, 1]])
Sign up to request clarification or add additional context in comments.

1 Comment

No problem. If this solves your problem, perhaps you could upvote / mark it as solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.