Matlab: loading a .mat file, why is it a struct? can I just have the stored vars loaded into memory?

37,066

Solution 1

As the documentation of LOAD indicates, if you call it with an output argument, the result is returned in a struct. If you do not call it with an output argument, the variables are created in the local workspace with the name as which they were saved.

For your function loadStructFromFile, if the saved variable name can have different names (I assume environmentName), you can return the variable by writing

function result = loadStructFromFile(fileName, environmentName) 
    tmp = load(fileName, environmentName);
    result = tmp.(environmentName); 

Solution 2

Even when you just specify a single variable name, LOAD will still output it in a structure. In your case, one option you have is to use the function STRUCT2CELL to convert the output from LOAD into a cell array, then return this result using a variable output argument list:

function varargout = loadStructFromFile(fileName,environmentName)
  varargout = struct2cell(load(fileName,environmentName));
end

Using VARARGOUT has the added benefit that, if environmentName matches multiple variables in the .MAT file, you can return them all from your function. For example, if your .MAT file has three variable N1, N2, and N3, and environmentName is N*, you can get them all by calling your functions with multiple outputs:

[N1,N2,N3] = loadStructFromFile('values.mat','N*');

Solution 3

It is an old post, but if it can be useful for some people:

When you load a structure, and you want to assign directly the subfields in the output structure, you can use structfun and the following command:

bigMatrixOUT = structfun(@(x) x,load('values.mat','bigMatrix'))

bigMatrixOUT will contain directly the fields of bigMatrix, and not bigMatrixOUT.bigMatrix

Solution 4

You can also try accessing the known field using dot notation so it all happens in one line of code.

bigMatrix = load('values.mat','bigMatrix').bigMatrix; 

or

bigMatrix = load('values.mat','bigMatrix').('bigMatrix'); 
Share:
37,066
NullVoxPopuli
Author by

NullVoxPopuli

I do stuff

Updated on October 08, 2020

Comments

  • NullVoxPopuli
    NullVoxPopuli over 3 years

    Relevant code:

    function result = loadStructFromFile(fileName, environmentName) 
        result = load(fileName, environmentName);
    
    
    bigMatrix = loadStructFromFile('values.mat','bigMatrix'); 
    

    But when I look in the workspace, it shows 'bigMatrix' as a 1x1 struct. When I click on the struct, however, it is the actual data (in this case a a 998x294 matrix).

  • andrgolubev
    andrgolubev about 4 years
    what an absolutely disgusting api design (of Matlab's load())... Thanks for the explanation though!