user1919730
user1919730

Reputation:

How to get all data from a struct?

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?

Upvotes: 7

Views: 34377

Answers (5)

Chose
Chose

Reputation: 91

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

Upvotes: 3

Ufos
Ufos

Reputation: 3305

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

Upvotes: 1

raggot
raggot

Reputation: 1012

A small correction to Sahinsu's answer:

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

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

Upvotes: 0

Pursuit
Pursuit

Reputation: 12345

Some useful access syntax:

someVar = ResponseData(1)  %Displays the first element
someVar = ResponseData(4)  %Displays the 4th element

To display them all, one after the next

for ix = 1:length(ResponseData)
    tmp = ResponseData(ix);
end

To get all the fieldnames

names = fieldnames(ResponseData)

To get all 5 data elements from the structure with the first field names, and put them into a cell array

ixFieldName = 1;
someCellArray = {  ResponseData.(ixFieldName{1})  }

Upvotes: 0

Sahisnu
Sahisnu

Reputation: 41

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.

Upvotes: 4

Related Questions