views:

42

answers:

3

Hey,

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

A: 

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.

Oli Charlesworth
But if you want to use load() in a function, there is no need for them to end up in the workspace?!Additionally in the first case, isn't there temporarly the 2x size of the variable used?
Thomas Feix
@Thomas: Sorry, I've corrected my edit. They end up in the current scope. No, there isn't twice as much memory used, because behind the scenes, `realData` and `temp.varName` will point at the same data structure (until that data is actually modified).
Oli Charlesworth
+3  A: 

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.

groovingandi
but this will also create a struct. the only exception is that the struct hast only realData.VarName instead of possible multiple fields.
Thomas Feix
then just do `load('filename.mat', 'VarName');` and the variable VarName will end up in your current scope, not in a struct.
groovingandi
A: 

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.

William Payne