Path: news.mathworks.com!not-for-mail
From: "Tim Davis" <davis@cise.ufl.edu>
Newsgroups: comp.soft-sys.matlab
Subject: Return empty sparse from a mex file
Date: Fri, 30 Oct 2009 16:11:03 +0000 (UTC)
Organization: University of Florida
Lines: 23
Message-ID: <hcf36n$83n$1@fred.mathworks.com>
References: <hc3s2q$fbd$1@fred.mathworks.com>
Reply-To: "Tim Davis" <davis@cise.ufl.edu>
NNTP-Posting-Host: webapp-05-blr.mathworks.com
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1256919063 8311 172.30.248.35 (30 Oct 2009 16:11:03 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Fri, 30 Oct 2009 16:11:03 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 45902
Xref: news.mathworks.com comp.soft-sys.matlab:581320


"Arne Vagren" <arne.vagren@gmail.com> wrote in message <hc3s2q$fbd$1@fred.mathworks.com>...
> Hello!
> 
> I'm trying to assemble and return a sparse matrix in a mex-function. At the end of the function, I try to correct for the actual number of non-zero entries in the following way (where Btu = mxGetPr(plhs[0]);):
> 
> "nbytes = actual_number_of_nonzeros*sizeof(*Btu);
>  newptr = mxRealloc(Btu,nbytes);     
>  mxSetPr(plhs[0], newptr); 
>         
>  nbytes = actual_number_of_nonzeros*sizeof(*ir);
>  newptr = mxRealloc(ir, nbytes);
>  mxSetIr(plhs[0], newptr);"
> 
> To test my function I have tried , the, excellent, spok-function, see http://www.mathworks.com/matlabcentral/fileexchange/20186-spok-checks-if-a-matlab-sparse-matrix-is-ok, which gives an ok except when the output is empty, i.e. nnz = 0. spok then returns the error message "double, but with no values present". The resulting matrix still seem to work fine but it's a little disturbing to have an error which I don't understand.
> 
> My question is thus: What should my function return if actual_number_of_nonzeros = 0?
> 
> Best regards
> Arne

You are right to be troubled; spok is correctly telling you that you have constructed an invalid matrix.  That matrix, with a NULL pointer for mxGetPr, will break MATLAB somewhere.  Not everywhere, so it may seem fine, but it is not valid.

nnzmax(A) must never be zero, even if nnz(A) is zero.  nnzmax(A)>=1 must always hold.