Path: news.mathworks.com!not-for-mail
From: "Tim Davis" <davis@cise.ufl.edu>
Newsgroups: comp.soft-sys.matlab
Subject: Re: Modifying MEX arguments in place?
Date: Thu, 14 Feb 2008 13:37:05 +0000 (UTC)
Organization: University of Florida
Lines: 68
Message-ID: <fp1g61$elr$1@fred.mathworks.com>
References: <fp0fqv$3gd$1@fred.mathworks.com> <fp0utr$4gr$1@fred.mathworks.com>
Reply-To: "Tim Davis" <davis@cise.ufl.edu>
NNTP-Posting-Host: webapp-02-blr.mathworks.com
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1202996225 15035 172.30.248.37 (14 Feb 2008 13:37:05 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Thu, 14 Feb 2008 13:37:05 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 45902
Xref: news.mathworks.com comp.soft-sys.matlab:451372



"Titus" <titus.edelhofer@mathworks.de> wrote in message
<fp0utr$4gr$1@fred.mathworks.com>...
> 
> "Petr Krysl" <pkryslNOSP@Mucsd.edu> schrieb im Newsbeitrag 
> news:fp0fqv$3gd$1@fred.mathworks.com...
> > For the MEX experts out there: I would like to factor a huge
> > matrix (passed in as a one-dimensional array) in-place in a
> > mex file.  Unfortunately, the documentation says there may
> > be side effects (and there are: the Matlab executive is
> > apparently getting all mixed up).
> >
> > Is there no way I could modify an argument in-place? If that
> > is not possible, the penalty would be huge.  We are talking
> > about a matrix of several gigabytes size...
> >
> > Thanks for your help.
> >
> > Petr
> 
> Hi,
> 
> besides the warnings given by others, I have another question:
> do you really need to do this in a mex file? And why?
> MATLAB provides some sort of in-place operation for
> variables, e.g.,
> 
> function X = somefunction(X)
> % modify X
> 
> and you call this function by
> 
> foo = somefunction(foo);
> 
> then MATLAB will actually not copy your matrix foo...
> 
> Titus 
> 
> 

James' advice is perfect.

Titus:  there are lots of things you can do in mexFunctions
that are too slow in M, or take too much memory.  So
sometimes you just can avoid going to C.

The new feature where MATLAB can avoid a memory copy in
functions like x=f(x) is really handy, but unfortunately
it's not made available to us mex authors.  At least not
yet.  It would be great if there could be query like:

if (mxIsThisVariableAShallowCopy (prhs [0]))
{
    oops, make a copy of prhs[0], and modify the copy
}
else
{
    modify prhs[0] in place
}
plhs [0] = prhs [0] ;

There would be lots of cool things a mexFunction could do if
it could modify its inputs (like a sparse cholupdate with an
O(1) best-case run time, for xample), but it's very dangerous.

The safest thing to do for a mexFunction that modifies its
inputs is to wrap it in an M-file that guarantees the
parameters to the hazardous mexFunction aren't a shallow
copy of another variable.