Matlab: Loading files

434 Views Asked by At

If I use the load function by matlab I normally end up doing something like this:

temp = load('filename.mat');
realData = temp.VarName;
clear temp

or

realData = load('filename.mat');
realData = realData.VarName;

is any of this methods superiour to the other, especially in terms of memory usage? Or is there a more direct approach to avoid this temporary struct?

Thx Thomas

3

There are 3 best solutions below

2
On BEST ANSWER

Well, if you just do load('filename.mat');, all the variables end up in the current scope.

I doubt there's any meaningful memory cost to either of your methods, though. Matlab uses copy-on-write.

0
On

You might want to try using the "importdata" command:

   szFilePath = 'c:\dirName\myData.mat';
   myData = importdata( szFilePath );

This avoids the implicit placement of variables into scope when load is used with no output arguments, as well as the unnecessary assignment-from-struct command.

As noted by Oli, the lazy copy (copy-on-write) behaviour means that memory considerations are moot.

From a maintenance/readability point of view importdata has a couple of advantages:

  1. Explicitly naming the variables that are created in the workspace documents what the function is doing much more clearly.
  2. Removing the necessity for the assignment-from-struct operation enables distracting and irrelevant operations to be removed from the source file.

I am using MATLAB R2010a.

2
On

If you know you need just specific variables from your matfile, you can do

realData = load('filename.mat', 'VarName');

See the Matlab documentation for more info about the load command.