Matlab: loading a .mat file, why is it a structure? Can I just save the saved Vars to memory?

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 structure. However, when I click on the structure, this is the actual data (in this case, the matrix is ​​998x294).

+7
source share
3 answers

As indicated in the LOAD documentation, if you call it with an output argument, the result is returned in a struct. If you do not call it using the output argument, the variables are created in the local workspace with the name that they saved.

For your loadStructFromFile function, if the name of the stored variable 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); 
+7
source

Even if you specify only one variable name, LOAD will still output it to the structure. In your case, one option that you have is to use the STRUCT2CELL function to convert the output from LOAD to an array of cells, then return this result using the list of variable output arguments :

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

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

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

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

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

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

bigMatrixOUT will directly contain bigMatrix fields, not bigMatrixOUT.bigMatrix

0
source

All Articles