Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: Cell Array of Function Handles Leaks Memory
Date: Sun, 1 Jun 2008 17:42:01 +0000 (UTC)
Organization: The MathWorks, Inc.
Lines: 68
Message-ID: <g1un19$s9r$1@fred.mathworks.com>
References: <g1t973$aeg$1@fred.mathworks.com> <g1tkd6$qi9$1@fred.mathworks.com> <g1udna$sgp$1@fred.mathworks.com> <g1ueot$67i$1@fred.mathworks.com> <g1ugqh$ip1$1@fred.mathworks.com> <g1uhsa$pi4$1@fred.mathworks.com> <g1ui7i$rmf$1@fred.mathworks.com> <g1uj99$4tr$1@fred.mathworks.com>
Reply-To: <HIDDEN>
NNTP-Posting-Host: webapp-03-blr.mathworks.com
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1212342121 28987 172.30.248.38 (1 Jun 2008 17:42:01 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Sun, 1 Jun 2008 17:42:01 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 1327593
Xref: news.mathworks.com comp.soft-sys.matlab:471651



"us " <us@neurol.unizh.ch> wrote in message
<g1uj99$4tr$1@fred.mathworks.com>...
> "NIcholas ":
> <SNIP mem leak...
> 
> > I am running Matlab version 7.0.0.19920 (R14) under 
> Windows XP. 
> > Do you get a memory leak using the code I posted above
> > under 2007b...
> 
> no, not here; system:
> ic2.2*2.3mhz/2g/winxp.sp2/2007b(7.5.0.342)
> 
> this might(!) indicate that the memory, which is visibly 
> attached to the function handle in 2007b is hidden in the 
> older version...
> therefore, this might(!) help
> 
>      clear cellArrayFunHandleLeaks;
> 
> just a thought
> us

I still have problems after using the clear
cellArrayFunHandleLeaks;

I have come up with a solution that would be acceptable if
there is no way to resolve this issue in older version of
MATLAB.

I am storing a structure array with a field for data
required by the function, and a field for the function,
written as a simple function in an m-file rather than an
anonymous function.  The function would be called by passing
in the desired argument followed by the data stored in data
field.

For the above example the fix would be:

function z=add(x,y)
    z=x+y;
end

function A = cellArrayFunHandleLeaks(method)
    B=ones(1000,1000);
    if method==1
        A.f = @(x) x+B;
    else
        A.f = @add;
        A.data = {B};
    end
end

% leaks memory
A = cellArrayFunHandleLeaks(1);
argIn = 1;
result = A.f(1);
clear all; 

% does not leak memory
A = cellArrayFunHandleLeaks(0);
argIn = 1;
result = A.f(1, A.data{:});
clear all;

The downside of this solution is that another m-file is
needed for each unique function and code for calling the
function is slightly longer.