Implicit assignment within functions

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view

Implicit assignment within functions

Hi Octavers

I discovered the following undocumented (I think) trick on a "I wonder if
that would work?" basis. It may prove useful.

Suppose you have saved variables, "X" ... , in a file "data.mat", say.

The following works:-

        function [X,...] = loadit(fname)
        eval(["load  " fname]);

    ... [ things you may want to do with the variables loaded ] ...


    Then executing

        [Y,...] = loadit("myfile.mat")

    will cause the variables Y,..., to be set to the values of the loaded
    variables X,..., without the necessity of making an assignment "X=..."
    within the body of the function. That is, an implicit assignment
    "X=..." has occurred during the load. "load -force " is not necessary.

Of course you have to know that the names of the variables stored in the
file are "X", etc, when defining the function "loadit" (but you have to
know this anyway, if you are going to "load" inside a function). The same
applies for further variable names. At the least I guess you save on
unnecessary duplicate usage of memory space.

One convenient usage of such a function is to load "X" from several
different files into different variables, e.g.

X0607_32 = loadit("o607_32.mat"); X0607_33 = loadit("o607_33.mat"); ...

without the re-copying the just-loaded X which you would have to do if you

load o607_32.mat; X0607_32 = X; load -force o607_33.mat; X0607_33 = X; etc

Best wishes,
Ted.                                    ([hidden email])