필터 지우기
필터 지우기

How to call a MATLAB variable loaded in from a .mat file when you don't know the name of the variable beforehand

조회 수: 6 (최근 30일)
I have a .mat file which contains a variable in it I want to perform some calculations on. The catch is I don't know the variable name beforehand.
I can load the variable just fine into my workspace using the who('-file',filepath) function to find the variable name, then the load() function to load the variable in (the .mat file only contains one variable, so I can just use the first entry in the variables_names array).
data=[1;2;3]; %generate data (real data is 4310x4310x150 matrix)
filename='matfile.mat'; %assign filename
save(filename,'data','-v7.3') %save data as .mat file (since actual data in code is large, using v7.3)
variable_names=who('-file',filename); %Grab the variable names in the .mat file
load(filename,variable_names{1}); %Using the only variable name in the .mat file, grab that variable.
Now, how do I perform calculations on the "data" file which can been loaded into be workspace? I can't call it directly because I don't know the name of the file beforehand. The easiest way would be to use eval():
new_data=eval(variable_names{1});
But that crashes my code (as all of the online forums told me it might). So, how do I assign the original values in the "data" array to this new variable "new data".
In my real code the data is generated in a compeltely different script than the data analysis is performed, so I can't just call the original "data" variable. Globals aren't really an option.

채택된 답변

Stephen23
Stephen23 2024년 1월 24일
편집: Stephen23 2024년 1월 24일
"The easiest way would be to use eval():"
Use STRUCT2CELL, e.g.:
C = struct2cell(load(filename));
D = C{1};
Avoid LOADing directly into the workspace.
By LOADing into an output argument your task is easy.

추가 답변 (1개)

Voss
Voss 2024년 1월 23일
variable_names = who('-file',filename);
S = load(filename,variable_names{1});
new_data = S.(variable_names{1});
  댓글 수: 2
Walter Roberson
Walter Roberson 2024년 1월 23일
S = load(filename,variable_names{1});
variable_names = fieldnames(S);
new_data = S.(variable_names{1});
Joshua Prince
Joshua Prince 2024년 1월 24일
I suspect these also would have worked, but the other answer was accepted because it allowed me to bypass grabbing the name of the file.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Whos에 대해 자세히 알아보기

제품


릴리스

R2022b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by