[Bf-python] matrix update

Gilbert, Joseph jgilbert at tigr.org
Thu Jan 15 19:22:45 CET 2004


Hi again. Anyway changing the matrix class a little from the union. The
original matrix class was using an array of pointers to float. Like:
Typedef float (matrixpointer*)[4]; Each float pointer was considered a
row and incrementing memory address for each column in the row.  I
changed this to simply a pointer to a pointer:

typedef float **ptRow;
typedef struct _Matrix {
	PyObject_VAR_HEAD
	ptRow matrixPtr;
	int rowSize;
	int colSize;
} MatrixObject;

To initialize the class you would simply allocate the number of float
pointers for rows and allocate the number of floats at each pointer for
the columns.  This way you can create any combination of 2, 3 and 4
dimensional arrays. The storage is not contigous but you can do much
more intuitive things like:
myMatrix->matrixPtr[Row][Column] = 5;

So the declaration takes a initialization array of floats (float *) or
NULL and the row and column dimensions for the array. Also the mathutils
class will allow integers, floats or a mixed int/float list for the
matrix initialization.  (I may have to clean it up)

Heres the init for the class:
PyObject * newMatrixObject (float * mat, int rowSize, int colSize) {
    MatrixObject    * self;
	int row, col;

	if (rowSize < 2 || rowSize > 4 || colSize < 2 || colSize > 4)
		return (EXPP_ReturnPyObjError (PyExc_RuntimeError,
                "row and column sizes must be between 2 and 4"));

    self = PyObject_NEW (MatrixObject, &matrix_Type);

	//create pointer array for rows
	self->matrixPtr = PyMem_Malloc(rowSize * sizeof(float*));

	for (row = 0; row < rowSize; row++){
		//allocate column float space at each row pointer
        self->matrixPtr[row] = PyMem_Malloc(colSize * sizeof(float));
        if (self->matrixPtr[row] == NULL){
            printf("\nFailure to allocate for row[%d]\n",row);
            return (EXPP_ReturnPyObjError (PyExc_MemoryError,
					"problem allocating non
contiguous array space\n"));
        }
    }

	if(mat){	//if a float array passed
		for (row = 0; row < rowSize; row++){
			for(col = 0; col < colSize; col++){
				self->matrixPtr[row][col] = mat[(row *
colSize) + col];
			}
		}
	}else{		//or if NULL passed
		for (row = 0; row < rowSize; row++){
			for (col = 0; col < colSize; col++){
				self->matrixPtr[row][col] = 0.0f;
			}
		}
	}

	//set size vars of matrix
	self->rowSize = rowSize;
	self->colSize = colSize;

    return ((PyObject *)self);
}



More information about the Bf-python mailing list