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

11 ビュー (過去 30 日間)
Archie
Archie 2016 年 10 月 31 日
回答済み: Walter Roberson 2016 年 10 月 31 日
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

採用された回答

Walter Roberson
Walter Roberson 2016 年 10 月 31 日
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.

その他の回答 (3 件)

James Tursa
James Tursa 2016 年 10 月 31 日
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 2016 年 10 月 31 日
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 2016 年 10 月 31 日
Thanks for the help.
I'll try bunching all the vectors together into a matrix and then load it manually before running the function!

カテゴリ

Help Center および File ExchangeWhos についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by