MATLAB: load from within function

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!

Answers


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.


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

Need Your Help

Locking an object from being accessed by multiple threads - Objective-C

objective-c ios multithreading

I have a question regarding thread safety in Objective-C. I've read a couple of other answers, some of the Apple documentation, and still have some doubts regarding this, so thought I'd ask my own