Reputation: 619
I read something about NumPy and it's Matrix class. In the documentation the authors write, that we can create only a 2 dimensional Matrix. So I think they mean you can only write something like this:
input = numpy.matrix( ((1,2), (3,4))
Is this right? But when I write code like this:
input = numpy.matrix( ((1,2), (3,4), (4,5)) )
it also works ... Normally I would say ok, why not, I'm not intrrested why it works. But I must write an exam for my univerity and so I must know if I've understood it right or do they mean something else with 2D Matrix?
Thanks for your help
Upvotes: 0
Views: 906
Reputation: 1885
emre.'s answer is correct, but I would still like to address the use of numpy matrices, which might be the root of your confusion.
When in doubt about using numpy.matrix
, go for ndarray
s :
Matrix
is actually a ndarray
subclass : Everything a matrix can do, ndarray
can do it (reverse is not exactly true).*
and **
operators, and any operation between a Matrix
and a ndarray
will return a matrix
, which is problematic for some algorithms.More on the ndarray
vs matrix
debate on this SO post, and specifically this short answer
From Numpy documentation
matrix
objects inherit from the ndarray and therefore, they have the same attributes and methods of ndarrays. There are six important differences of matrix objects, however, that may lead to unexpected results when you use matrices but expect them to act like arrays:
Matrix objects can be created using a string notation to allow Matlab-style syntax where spaces separate columns and semicolons (‘;’) separate rows.
Matrix objects are always two-dimensional. This has far-reaching implications, in that m.ravel() is still two-dimensional (with a 1 in the first dimension) and item selection returns two-dimensional objects so that sequence behavior is fundamentally different than arrays.
Matrix objects over-ride multiplication to be matrix-multiplication. Make sure you understand this for functions that you may want to receive matrices. Especially in light of the fact that asanyarray(m) returns a matrix when m is a matrix.
Matrix objects over-ride power to be matrix raised to a power. The same warning about using power inside a function that uses asanyarray(...) to get an array object holds for this fact.
The default
__array_priority__
of matrix objects is 10.0, and therefore mixed operations with ndarrays always produce matrices.Matrices have special attributes which make calculations easier. [...]
Upvotes: 0
Reputation: 1296
They both are 2D matrixes. The first one is 2x2 2D matrix and the second one is 3x2 2D matrix. It is very similar to 2D arrays in programming. The second matrix is defined as int matrix[3][2]
in C for example.
Then, a 3D matrix means that it has the following definition: int 3d_array[3][2][3]
.
In numpy, if i try this with a 3d matrix:
>>> input = numpy.matrix((((2, 3), (4, 5)), ((6, 7), (8, 9))))
ValueError: matrix must be 2-dimensional
Upvotes: 4