3

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

1
  • What do you mean by "matrix"? Is it numpy.matrix class? Commented Feb 21, 2009 at 18:45

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

1 Comment

OP asks numpy.matrix but zeros returns ndarray.
3

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.

Comments

Your Answer

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