passing lots of variables between function efficiently?

Hi
I have a question here.
I want to passing lots of variables between different function.
I defined those variables in a m file. And my other m files (functions) need use those variables.
How can I efficiently share those variables?
I know I can define a structure to put all the variables.
But every time I need use those variables I need write down lots of line at the beginning such as
nelx = Prob.nelx;
nely = Prob.nely;
...
...
...
I was wondering is there any other ways to do that?

 Accepted Answer

Using a single struct obtained from a dedicated M-function is a really good strategy already: It keeps the definition in one file, is memory efficient and clean.
Please note that expressions like nely = Prob.nely do not copy the data, if this array has more than 1 element. Matlab uses shared data copies instead, which means that the variable nely points to the same values in the memory as the field Prob.nely.
The function FEX: structvars copies the fields of a struct automatically to variables. But this is prone to programming errors, e.g. if the function needs to use a field, which you forgot to define in the struct - then the resulting error message will be confusing, while a nely = Prob.nely would create a clear message like "there is no field 'nely' in the struct". In addition creating variables dynamically does not allow Matlab's JIT accelerator to work efficiently, such that the total performance of your program will be lower.
Summary: Your current approach is efficient, clean and clear already.

More Answers (3)

Instead of writing statements like
nelx = Prob.nelx;
nely = Prob.nely;
You can do your computations on Prob.nelx and Prob.nely, i.e, in your code you simply prefix each nelx, nely, ... by a 'Prob.', e.g,
x = 123*Prob.nelx + 2*Prob.nely;
You create your variables in the workspace and save them with "save command" , per example if you create two variables a and b, then : save youfilename a b
in different M-files you load the file with "load" function :
load yourfilename

5 Comments

Will reading file low the code efficiency a lot?
i do not think so, anyway i proposed a way out, use tic toc commands with load and without load and conclude .
Going to disk is always going to be slower than staying in memory.
ok then put all your functions in one signle M-file and make your variables global .
>>doc global
Writing to disk will definitely a bottleneck in your program. Global variables are a bad idea also: Even if this would accelerate the program by some percent, the debugging and maintenance of the code will require much more time, which is more likely to waste days or weeks.

Sign in to comment.

Why not simply pass (part of) the structure around those functions?

Tags

Asked:

Kai
on 11 Feb 2013

Community Treasure Hunt

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

Start Hunting!