Access elements/fields from a struct
718 views (last 30 days)
I am generating a struct variable, returned from a SOAP API query, and am struggling to access the elements or fields contained within the struct.
When ever use: I 'disp(structVariable)'
It returns the dimensions of the struct.
I do not know the fieldnames contained in the struct either.
Is there an easy way to access a struct without knowing the fieldnames, then maybe send each element to a text file?
More Answers (3)
Tom on 25 Jun 2013
Edited: Jan on 8 Feb 2018
Structures can be referenced dynamically, i.e. using variable names not strings the user has written. In this case you have to put brackets around the dynamic reference.
is the same as
n = 'a';
can be used instead. the FIELDNAMES function can be used to get the field names of a structure.
S.a = 'test';
S.b = 1;
S.c = rand(2);
fNames = fieldnames(S);
for n = 1:length(fNames)
You can then use FPRINTF or something similar to write to a text file.
Muthu Annamalai on 25 Jun 2013
In addition to the excellent answers posted by @Iain, and @Tom, you may also want to look at MATLAB support for JSON from the FileExchange http://www.mathworks.com/matlabcentral/fileexchange/33381-jsonlab-a-toolbox-to-encodedecode-json-files-in-matlaboctave
Image Analyst on 25 Jun 2013
You can just type the variable name on the command line, or as just a single line in a script, to learn what the field names are. No semicolon or anything. Just the variable name itself:
It will show you what the field names are, and their values. Then, once you know that, you can write code to write them out to a text file using fprintf(). If you don't know the fields and the fields change all the time, then you can use code the others gave you. But I don't think this is your case - in your case the variable returned from your SOAP API query will have the same fields every time, right? What does it show when you put "structVariable" on its own line?