core/matlab/examples/mx/mxsetnzmax.c

00001 /*=================================================================
00002  * mxsetnzmax.c 
00003  *
00004  * mxsetnzmax takes a sparse matrix for an input. If the actual number
00005  * of non-zeros is not equal to the non-zero maximum for this sparse
00006  * matrix, it re-allocates the smaller amount of memory for the
00007  * sparse matrix. It then resets the values of pr, pi,ir and nzmax.
00008  *
00009  * This is a MEX-file for MATLAB.  
00010  * Copyright 1984-2006 The MathWorks, Inc.
00011  * All rights reserved.
00012  *=================================================================*/
00013 
00014 #include "mex.h"
00015 
00016 void mexFunction(
00017                  int nlhs,       mxArray *plhs[],
00018                  int nrhs, const mxArray *prhs[]
00019          )
00020 {
00021     mwSize actual_number_of_non_zeros;
00022    
00023     /* Check for proper number of input and output arguments */    
00024     if (nrhs != 1) {
00025         mexErrMsgTxt("One input argument required.");
00026     } 
00027     if(nlhs > 1){
00028         mexErrMsgTxt("Too many output arguments.");
00029     }
00030         
00031     if(!mxIsSparse(prhs[0])) {
00032     mexErrMsgTxt("Input argument must be sparse\n");
00033     }
00034 
00035     plhs[0] = mxDuplicateArray(prhs[0]);
00036     actual_number_of_non_zeros = mxGetJc(plhs[0])[mxGetN(plhs[0])];
00037     if(mxGetNzmax(plhs[0]) == actual_number_of_non_zeros) {
00038     mexWarnMsgTxt("The actual number of non-zeros is already equal to the non-zero maximum for this sparse matrix.\n");
00039     } else {
00040     
00041     double *ptr;
00042     void *newptr;
00043     mwIndex *ir;
00044     size_t nbytes;
00045 
00046     nbytes = actual_number_of_non_zeros * sizeof(*ptr);
00047     ptr = mxGetPr(plhs[0]);
00048     newptr = mxRealloc(ptr, nbytes);
00049     mxSetPr(plhs[0], newptr);
00050     ptr = mxGetPi(plhs[0]);
00051     if(ptr != NULL) {
00052         newptr = mxRealloc(ptr, nbytes);
00053         mxSetPi(plhs[0], newptr);
00054     }
00055     nbytes = actual_number_of_non_zeros * sizeof(*ir);
00056     ir = mxGetIr(plhs[0]);
00057     newptr = mxRealloc(ir, nbytes);
00058     mxSetIr(plhs[0], newptr);
00059     mxSetNzmax(plhs[0],actual_number_of_non_zeros);
00060     }
00061 }

GridLAB-DTM Version 1.0
An open-source project initiated by the US Department of Energy