[Numpy-discussion] How to construct a complex matrix in a C module?

Vanroose vanroose at ruca.ua.ac.be
Wed May 3 10:17:11 CDT 2000


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"??


Wim Vanroose




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;
  data = calloc(M*M+1,sizeof(Py_complex));
  for(n=0;n < M;n++){
    for(m=0; m<M; m++){
      p.real=x;
      p.imag=y;
      data[n*M+m] = p;
    }
  }
  result = (PyArrayObject
*)PyArray_FromDims(2,dimensions,PyArray_CDOUBLE);
  memcpy(result->data,data,M*M*sizeof(Py_complex));
  return PyArray_Return(result);return
PyComplex_FromDoubles(data[1].real,data[1].imag);
  free(data);
}

Wim Vanroose





More information about the Numpy-discussion mailing list