views:

635

answers:

2

I read the documentation on NumPy C API I could find, but still wasn't able to find out whether there is a possibility to construct a matrix object with C API — not a two-dimensional array. The function is intended for work with math matrices, and I don't want strange results if the user calls matrix multiplication forgetting to convert this value from an array to a matrix (multiplication and exponentiation being the only difference that matrix subclass has).

+3  A: 

numpy.matrix is an ordinary class defined in numpy/core/defmatrix.py. You can construct it using C API as any other instance of user-defined class in Python.

J.F. Sebastian
+5  A: 

You can call any python callable with the PyObject_Call* functions.

PyObject *numpy = PyImport_ImportModule("numpy");
PyObject *numpy_matrix = PyObject_GetAttrString(numpy, "matrix");
PyObject *my_matrix = PyObject_CallFunction(numpy_matrix, "(s)", "0 0; 0 0");

This will create a matrix my_matrix of size 2x2.

EDIT: Changed references to numpy.zeros/numpy.ndarray to numpy.matrix instead.

I also found a good tutorial on the subject: http://starship.python.net/crew/hinsen/NumPyExtensions.html

MizardX
OP asks `numpy.matrix` but `zeros` returns `ndarray`.
J.F. Sebastian