How to get all data from a struct?

30,257

Solution 1

or you can use cellfun function:

% STRUCT - your structure
% tmp_nam - structure field names
% tmp_val - values for structure field names


tmp_nam = fieldnames(STRUCT);
tmp_val = cellfun(@(x)(STRUCT.(x)),tmp_nam,'UniformOutput',false);

Solution 2

You may use fieldnames to get the data from the struct and then iteratively display the data using getfield function. For example:

structvariable = struct('a',123,'b',456,'c',789);
dataout = zeros(1,length(structvariable)) % Preallocating data for structure
field = fieldnames(a);

for i = 1:length(structvariable)
    getfield(structvariable,field{i})
end

Remember, getfield gives data in form of cell, not matrix.

Solution 3

In order to display all elements and subelements of a structure there is a custom function that you can download here: http://www.mathworks.com/matlabcentral/fileexchange/13831-structure-display

Share:
30,257
Admin
Author by

Admin

Updated on July 09, 2022

Comments

  • Admin
    Admin almost 2 years

    I've got a result from a web service and MatLab gladly notifies that it is a 1x1 struct. However, when I try to display it (by typing receivedData and pressing enter) I get to see this:

    ResponseData: [5x1 struct]
    

    Equally gladly, I entered the following, in my attempt to get the data viewed to me:

    struct2array(responseData)
    

    I get only a bunch (not five, more than five) of strings that might be names headers of columns of the data provided.

    How do I get all the data from such structure?

  • Admin
    Admin about 11 years
    But what about a data structure that I don't know what it looks like? I'd like a generic method for getting data out of such structures. For instance, how do I iterate and display all the values in the structure? I know how to do such operations in Java but MatLab scares me a bit.
  • Sahisnu
    Sahisnu about 11 years
    The method I provide can give you all values of the structure, because it iterates all fields inside of structure. fieldnames is used to get all the field names of the struct, and getfield gets all the data in the specific field of the struct.