How to acces a variable in structure when i only have the string saved into a variable

조회 수: 4 (최근 30일)
Hello,
Here is my code :
[filename, pathname] = uigetfile('*.mat', 'Select the MATLAB mat file');
a = load(filename);
I'm asking a file to the user. And then loading the array of the coresponding file into a. But it is saved as a Structure. a is a Structure that contained a variable named by the name of the filename. Which is itself containing the array. Am I right ? After that I want to plot it.
plot(a.??);
The problem is, that i can't right a.filename. Cause filename is not the real name, but the name of the varaible that contain the string I want.
I hope you'll understand my problem.
Thank you in advance.
  댓글 수: 2
Adam
Adam 2014년 8월 28일
Are you expecting the user to have saved a specifically named variable in their .mat file?
Otherwise there could be any number of variables being loaded in when you load the file.
Adrien
Adrien 2014년 8월 28일
Yes. Is the mat file not like a structure ? You can save for example :
a = load ('****.mat')
Than :
a =
aaa: [1x100 double]
bbb: [1x100 double]
How can i access for example aaa without knowing aaa. But only the name of the file and the position into the file. I mean aaa is now 1.

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

채택된 답변

Jos (10584)
Jos (10584) 2014년 8월 28일
This would be an approach
[filename, pathname] = uigetfile('*.mat', 'Select the MATLAB mat file');
tmp = load(filename);
fn = fieldnames(tmp) ;
X = tmp.(fn{1}) ; % simply take the first (and may be only) variable)
plot(X) % use X in the remainder of the code
or if you know that you want to load a specific variable from the matlfile
tmp = load(filename)
varname = 'MyDataVar' ;
if ~isfield(tmp, varname)
error('The file %s does not contain the variable "%s",filename, varname)
else
X = tmp.(varname) ;
end
and this might also do the trick:
tmp = load(filename,varname)

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by