MATLAB: Avoid load filename.mat in every function-file called from a main-script-file

functions

I'm quite new to Matlab, so Im still unused to some terminology.
Now I have many functions, and every function is within their own matlab-file. The functions I call from a main script-file where i call the functions, disp their results and more.
In many of the functions I use
load datafile.mat,
loading the same datafile (that contains matrices and vectors) in many functions. Now Im looking for a way to avoid loading the datafile so many times, and just do it for all functions in just a bit of code. Maybe this is to be done from within the scripting-file? How exactly can this be done.
Also there are some lines of code I consistently use in several functions, is there a way to just have these lines of code in one place? Here is an example of the code I reuse:
[pX sX] = size(X);
Also another thing I'd like is to avoid having to call a function from within another function if that's possible? Cause some functions are "reused" several times in different functions?

Best Answer

You can load the data file once and provide the values by using it as input arguments of the called functions:
function YourMainFunction
Data = load('datafile.mat'); % Never LOAD without catching the output
YourFunc1(Data);
YourFunc2(Data);
...
It is the best way to create tiny values like in [pX sX] = size(X) locally. It takes just some micro-seconds, but when you debug the code or modify it, you need at least minutes to get the overview.
There is no problem with re-using functions. So please explain why you want to avoid this. Usually it is the goal of each professional programmer to re-use as many code as possible, because this reduces the time for programming and debugging.