Matlab: loading a .mat file, why is it a struct? can I just have the stored vars loaded into memory?
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);
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*');
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