Thread Subject: Saving an anonymous function handle to a mat-file

Subject: Saving an anonymous function handle to a mat-file

From: Christian Zietz

Date: 12 Sep, 2008 12:34:49

Message: 1 of 15

Hi,

when I enter

y = 1;
f = @(x)(x+y);
save foobar f;

in the MATLAB command window, the resulting foobar.mat will load and
work when copied to another computer.

When I execute the same code inside a function and copy foobat.mat,
MATLAB on the other computer needs the m-file containing the function
where I defined the function handle "f" to load foobar.mat.

What can I do to change this?

Christian

Subject: Saving an anonymous function handle to a mat-file

From: Matt

Date: 12 Sep, 2008 16:55:04

Message: 2 of 15

Christian Zietz <newsgroup@chzsoft.com.ar> wrote in message <6iv5vcFn3i0U1@mid.individual.net>...
> Hi,
>
> when I enter
>
> y = 1;
> f = @(x)(x+y);
> save foobar f;
>
> in the MATLAB command window, the resulting foobar.mat will load and
> work when copied to another computer.
>
> When I execute the same code inside a function and copy foobat.mat,
> MATLAB on the other computer needs the m-file containing the function
> where I defined the function handle "f" to load foobar.mat.
>
> What can I do to change this?
>
> Christian

You could do func2str(f) and save the function as a string. Then reconvert it using eval when loading it back in from the .mat file

y = 1;
f = @(x)(x+y);
fstr=func2str(f)
save foobar fstr;


Then later


load foobar fstr;
f=eval(fstr);






Subject: Saving an anonymous function handle to a mat-file

From: Christian Zietz

Date: 12 Sep, 2008 17:10:44

Message: 3 of 15

Matt schrieb:

> You could do func2str(f) and save the function as a string. Then
> reconvert it using eval when loading it back in from the .mat file

> y = 1;
> f = @(x)(x+y);
> fstr=func2str(f)
> save foobar fstr;

> Then later

> load foobar fstr;
> f=eval(fstr);

This won't work unless I also save all variables involved in the
anonymous function (in this case it's only "y"), because "y" will be
undefined (or even worse: have another value) when I reload foobar.mat
and evaluate "fstr".

Christian
--
Christian Zietz - CHZ-Soft - czietz (at) gmx.net
WWW: http://www.chzsoft.com.ar/
PGP/GnuPG-Key-ID: 0x6DA025CA

Subject: Saving an anonymous function handle to a mat-file

From: Bruno Luong

Date: 12 Sep, 2008 17:15:05

Message: 4 of 15

"Matt " <mjacobson.removethis@xorantech.com> wrote in message <gae6t8$7de$1@fred.mathworks.com>...

>
> load foobar fstr;
> f=eval(fstr);
>

But the variable y=1 is lost for ever...

Bruno

Subject: Saving an anonymous function handle to a mat-file

From: Matt

Date: 12 Sep, 2008 17:39:02

Message: 5 of 15


> This won't work unless I also save all variables involved in the
> anonymous function (in this case it's only "y"), because "y" will be
> undefined (or even worse: have another value) when I reload foobar.mat
> and evaluate "fstr".

That's right it won't, but you never discussed the role of y in your original post, so I could only assume that it is a parameter that would be made available when the function was loaded back in.

One approach would be to do

strrep(fstr,y,numstr(y));

before saving.

You could also consider setting up f() as an inline function instead of an anonymous one, in a similar way.


Subject: Saving an anonymous function handle to a mat-file

From: Matt

Date: 12 Sep, 2008 17:52:01

Message: 6 of 15

"Matt " <mjacobson.removethis@xorantech.com> wrote in message <gae9fm$r7n$1@fred.mathworks.com>...
>
> > This won't work unless I also save all variables involved in the
> > anonymous function (in this case it's only "y"), because "y" will be
> > undefined (or even worse: have another value) when I reload foobar.mat
> > and evaluate "fstr".


I think I misunderstood you earlier.

No, when you execute

>>f=eval(fstr)

the result is

f =

    @(x)(x+y)


In other words, all that happens is that fstr is converted from a string back to an anonymous function, f. It does not matter whether y exists in memory, at that point.

Of course, if you then try to evaluate the anonymous function f(x), you will get an error unless you first provide y, but presumably you have a way of doing that. Otherwise, why would you want to re-use the function on a different machine?




Subject: Saving an anonymous function handle to a mat-file

From: Bruno Luong

Date: 12 Sep, 2008 18:16:01

Message: 7 of 15

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

Subject: Saving an anonymous function handle to a mat-file

From: Christian Zietz

Date: 12 Sep, 2008 18:19:55

Message: 8 of 15

Matt schrieb:

> Of course, if you then try to evaluate the anonymous function f(x),
> you will get an error unless you first provide y, but presumably you
> have a way of doing that. Otherwise, why would you want to re-use the
> function on a different machine?

When you declare a function handle, MATLAB "freezes" the current
workspace and saves it together with the function handle. You can go

y = 1;
f = @(x)(x+y)
clear y;

and

f(3)

will still evaluate to 4. Even if you now enter

y = pi;

f(3) will still be 4.

When you save a function handle to a mat-file the workspace at the time
the function was defined is also saved. This obviously doesn't happen if
you just save the string that is func2str(f).

Christian
--
Christian Zietz - CHZ-Soft - czietz (at) gmx.net
WWW: http://www.chzsoft.com.ar/
PGP/GnuPG-Key-ID: 0x6DA025CA

Subject: Saving an anonymous function handle to a mat-file

From: Christian Zietz

Date: 12 Sep, 2008 18:22:09

Message: 9 of 15

I wrote:

> When you declare a function handle, MATLAB "freezes" the current
> workspace and saves it together with the function handle.

PS:
<http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_prog/f4-70115.html#f4-71621>

Christian
--
Christian Zietz - CHZ-Soft - czietz (at) gmx.net
WWW: http://www.chzsoft.com.ar/
PGP/GnuPG-Key-ID: 0x6DA025CA

Subject: Saving an anonymous function handle to a mat-file

From: Bruno Luong

Date: 12 Sep, 2008 18:50:18

Message: 10 of 15

This loadfun should be safer:

function fun___=loadfun(file)

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

clear file data;

evalvar(sfun___);

fun___ = sfun___.function;
clear sfun___;
fun___=eval(fun___);

end

% nested function
function evalvar(sfun)

for n=1:length(sfun.workspace)
    wn = sfun.workspace{n};
    vlist=fieldnames(wn);
    for k=1:length(vlist)
        val = wn.(vlist{k});
        assignin('caller',vlist{k}, val);
    end
end

end

% Bruno

Subject: Saving an anonymous function handle to a mat-file

From: Christian Zietz

Date: 12 Sep, 2008 18:56:38

Message: 11 of 15

Bruno Luong schrieb:

> This loadfun should be safer:

Thank you very much! I'll give it a try as soon as I'm back at the
computer where MATLAB is installed.

Christian
--
Christian Zietz - CHZ-Soft - czietz (at) gmx.net
WWW: http://www.chzsoft.com.ar/
PGP/GnuPG-Key-ID: 0x6DA025CA

Subject: Saving an anonymous function handle to a mat-file

From: Matt

Date: 12 Sep, 2008 19:42:02

Message: 12 of 15


> PS:
> <http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_prog/f4-70115.html#f4-71621>
>
> Christian


OK. good to know...

Subject: Saving an anonymous function handle to a mat-file

From: Matt

Date: 12 Sep, 2008 20:54:03

Message: 13 of 15


> When I execute the same code inside a function and copy foobat.mat,
> MATLAB on the other computer needs the m-file containing the function
> where I defined the function handle "f" to load foobar.mat.

So why does this happen? If anonymous functions carry their own internal snapshots of the workspace, what would it be trying to recover from the m-file where it was born?

Subject: Saving an anonymous function handle to a mat-file

From: Bruno Luong

Date: 12 Sep, 2008 21:44:02

Message: 14 of 15

"Matt " <mjacobson.removethis@xorantech.com> wrote in message <gaektb$glf$1@fred.mathworks.com>...
>
> what would it be trying to recover from the m-file where it was born?
>

Something such as anonymous nested functions of the local m-file.

If the mfile is modified/changed/deleted, such information is of course lost together with the m-file that carries the anonymous function.

Bruno

Subject: Saving an anonymous function handle to a mat-file

From: Matt

Date: 12 Sep, 2008 22:13:02

Message: 15 of 15

"Bruno Luong" <b.luong@fogale.findmycountry> wrote in message <gaenr2$dc7$1@fred.mathworks.com>...
> "Matt " <mjacobson.removethis@xorantech.com> wrote in message <gaektb$glf$1@fred.mathworks.com>...
> >
> > what would it be trying to recover from the m-file where it was born?
> >
>
> Something such as anonymous nested functions of the local m-file.
>
> If the mfile is modified/changed/deleted, such information is of course lost together with the m-file that carries the anonymous function.
>
> Bruno

That makes sense, but that surely doesn't explain why something as simple as @(x) (x+y) is a problem.

Tags for this Thread

Add a New Tag:

Separated by commas
Ex.: root locus, bode

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

rssFeed for this Thread

Public Submission Policy

NOTICE: Any content you submit to MATLAB Central, including personal information, is not subject to the protections which may be afforded information collected under other sections of The MathWorks, Inc. Web site. You are entirely responsible for all content that you upload, post, e-mail, transmit or otherwise make available via MATLAB Central. The MathWorks does not control the content posted by visitors to MATLAB Central and, does not guarantee the accuracy, integrity, or quality of such content. Under no circumstances will The MathWorks be liable in any way for any content not authored by The MathWorks, or any loss or damage of any kind incurred as a result of the use of any content posted, e-mailed, transmitted or otherwise made available via MATLAB Central. Read the complete Disclaimer prior to use.

Contact us at files@mathworks.com