
Dear Numerical Python users,
I am new to the numerical python and extending python in C. I am making a module that involves the construction of complex matrices. But first, I really want to understand how these matrices are constructed. Here is an example function that constructs a matrix of size M and puts on each position a complex number "x+I y". x and y are arguments when you call the function in python.
My question: Is this the right way of organising the construction of a complex matrix. Are there easier ways? Can I construct the matrix directly in "result->data"??
Yes, you can create the array, point a pointer to "result->data" and fill it in. Internally, when the array is created an equivalent malloc is performed. I've changed your code below to eliminate the unecessary copying.
static PyObject* matrix(PyObject *self, PyObject *args){ double x,y; int size; int M,n,m; PyArrayObject *result; int dimensions[2]; Py_complex *data; Py_complex p; if(!PyArg_ParseTuple(args,"idd",&M,&x,&y)) return NULL; dimensions[0] = M; dimensions[1] = M;
result = (PyArrayObject *)PyArray_FromDims(2,dimensions,PyArray_CDOUBLE);
data = result->data; for(n=0;n < M;n++){ for(m=0; m<M; m++){ p.real=x; p.imag=y; data[n*M+m] = p; } }
return PyArray_Return(result);return PyComplex_FromDoubles(data[1].real,data[1].imag); free(data); }
Welcome to the wonderful world of NumPy. -Travis

Dear Travis Oliphant, The pointer result->data is of type (char *). So I still have to do a cast data = (Py_complex *)result->data; Best Wishes Wim Vanroose Travis Oliphant wrote:
Yes, you can create the array, point a pointer to "result->data" and fill it in. Internally, when the array is created an equivalent malloc is performed.
I've changed your code below to eliminate the unecessary copying.
static PyObject* matrix(PyObject *self, PyObject *args){ double x,y; int size; int M,n,m; PyArrayObject *result; int dimensions[2]; Py_complex *data; Py_complex p; if(!PyArg_ParseTuple(args,"idd",&M,&x,&y)) return NULL; dimensions[0] = M; dimensions[1] = M;
result = (PyArrayObject *)PyArray_FromDims(2,dimensions,PyArray_CDOUBLE);
data = result->data; for(n=0;n < M;n++){ for(m=0; m<M; m++){ p.real=x; p.imag=y; data[n*M+m] = p; } }
return PyArray_Return(result); free(data); }
Welcome to the wonderful world of NumPy.
-Travis
participants (2)
-
Travis Oliphant
-
Vanroose Wim