Path: news.mathworks.com!not-for-mail
From: "Bruno Luong" <b.luong@fogale.findmycountry>
Newsgroups: comp.soft-sys.matlab
Subject: Re: Saving an anonymous function handle to a mat-file
Date: Fri, 12 Sep 2008 18:16:01 +0000 (UTC)
Organization: FOGALE nanotech
Lines: 57
Message-ID: <gaebl1$sl0$1@fred.mathworks.com>
References: <6iv5vcFn3i0U1@mid.individual.net>
Reply-To: "Bruno Luong" <b.luong@fogale.findmycountry>
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 1221243361 29344 172.30.248.35 (12 Sep 2008 18:16:01 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Fri, 12 Sep 2008 18:16:01 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 390839
Xref: news.mathworks.com comp.soft-sys.matlab:490034



Christian Zietz <newsgroup@chzsoft.com.ar> wrote in message <6iv5vcFn3i0U1@mid.individual.net>...

> 
> What can I do to change this?
> 

Please try this:

% file savefun.m
function savefun(file, f)

sfun = functions(f);
sfun.file = '';
save(file,'sfun');

% file loadfun.m
function f=loadfun(file)

data=load(file);
sfun = data.sfun;

for n=1:length(sfun.workspace)
    wn = sfun.workspace{n};
    vlist=fieldnames(wn);
    for k=1:length(vlist)
        val = wn.(vlist{k}); %#ok
        eval([vlist{k} '= val;']);
    end
end
f=eval(sfun.function);

% file t.m
function t

y = 1;
f = @(x)(x+y);
savefun('foo.mat', f);

% end t

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Now try this in command line

>> t % save anonymous function inside a function
>> f=loadfun('foo.mat') % load in workspace

f = 

    @(x)(x+y)

>> f(0) % evaluate

ans =

     1

% Bruno