How to make a function that loads its own input variables?
6 views (last 30 days)
Show older comments
Archie
on 31 Oct 2016
Answered: Walter Roberson
on 31 Oct 2016
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
0 Comments
Accepted Answer
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.
0 Comments
More Answers (3)
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.
0 Comments
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.
0 Comments
See Also
Categories
Find more on Whos in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!