7

I have a MATLAB function that needs access to the data of some largeFile.mat. If (to avoid polluting the global namespace) I put the load command within the function, will MATLAB reload largeFile every time the function is called, or is it smart enough to cache largeFile between calls? E.g.

function hello()
    load largeFile.mat;
    display('hi');
end

for i=1:1000
    hello();
end

Should I keep the load command within the function, or should I do it once and pass the largeFile's data in as an arg? Thanks!

2 Answers 2

18

The solution from Ghaul (loading the data into a structure and passing it as an argument) is what I would typically suggest since it avoids having to hardcode file names/paths into your functions, which require you to edit your function every time the file name or location changes.

However, for the sake of completeness there is another solution: use persistent variables. These are variables local to the function that retain their values in memory between calls to the function. For your situation, you could do this:

function hello()
  persistent data;  %# Declare data as a persistent variable
  if isempty(data)  %# Check if it is empty (i.e. not initialized)
    data = load('largeFile.mat');  %# Initialize data with the .MAT file contents
  end
  display('hi');
end
Sign up to request clarification or add additional context in comments.

Comments

6

Matlab will load it every time it is called, so it is much faster to call it once and give it as input. If you don't want to clutter your workspace, I suggest you load your file into a structure, like this

L = load('largeFile.mat');

EDIT: I did a quick test on your hello() function and one of my .mat files. Loading it inside the function and running it 100 times I used 43.29 seconds. Loading it once and giving it as input took 0.41 seconds for 100 runs, so the time difference is huge.

1 Comment

Thanks for timing the comparison!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.