How to make a function that loads its own input variables?

6 views (last 30 days)
Hi there, I'm rather new to MATLAB and I'm trying to make a function which will have lots of potential input variables. For this reason I do not want to load them all to the workspace before I run the function. I'm sure I'm being dense, but there must be a way for a function to load its own input variables from a file on the path?
Hopefully this will clear up my aims:
Many thanks for any help

Accepted Answer

Walter Roberson
Walter Roberson on 31 Oct 2016
The syntax that you show "poofs variables into existence", which is incompatible with using a Static Workspace (which is signaled by using an end statement matching the function statement.) For static workspaces, you need to assign the output of load() to a variable. If it is a .mat you are loading, that will create a struct that has one field for each variable in the workspace. For example,
v_struct = load('vect1');
m_struct = load('mat1');
vect1 = v_struct.vect1;
mat1 = m_struct.mat1;
As others have pointed out, this will be quite inefficient if you are calling the function in a loop.

More Answers (3)

James Tursa
James Tursa on 31 Oct 2016
Start with this:
doc save
doc load
Although, you could put everything in a struct and then pass that one struct (instead of passing many individual variables). Then extract the struct fields inside your function.

John D'Errico
John D'Errico on 31 Oct 2016
Shiver. Kind of a bad idea. You can do it, but a poor choice of interface as you learn to program. Frequent loads are going to be slow, something you will not enjoy doing too often.
Better is to put them all into one .mat file. Then you could do one load. But if you are going to do that, you still will need to use load. And having a load inside your functions is again poor programming, as it is slow.
So better is to store all of your data in one structure. Then you can just pass it into your function as a single argument, and you avoid all of those spurious loads.

Archie
Archie on 31 Oct 2016
Thanks for the help.
I'll try bunching all the vectors together into a matrix and then load it manually before running the function!

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!