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

Deadly 提交于 2019-12-06 23:13:04

问题


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).


回答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); 



回答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*');



回答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



来源:https://stackoverflow.com/questions/4718417/matlab-loading-a-mat-file-why-is-it-a-struct-can-i-just-have-the-stored-vars

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!