How to get all data from a struct? - matlab

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?

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.

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

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

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

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

Related

Extract structures in a loop

I have a structure ('data'), with 26 fields (A, B, C, D, etc.). Each field contains 1x30 cells (one for each participant), and each cell contains a structure.
I would like to extract all the structures (i.e., one structure per field) corresponding to each participant. That is, I would like to obtain 30 new ‘data’, each with 26 fields, and each field containing 1x1 structure, with the structure corresponding to the participant. I have tried the following code:
data = load('D:\filepath\mydata.mat'); %load file with data. 1x1 struct.
all_fields = fieldnames(data); %store the fields of the structure. 26x1 cell.
forStr = length(all_fields); %26
n_ppts = 30; %total number of participants.
%for each participant, extract the corresponding structure in each field.
for nn = 1:n_ppts
for idx_field = 1:forStr
name_field = all_fields{idx_field};
data2 = data;
data2.(name_field) = data.(name_field){nn};
end
%save the 'data' for each participant. The 'data' should include 26 fields, and 1 structure for each field.
name = ppt_fname(nn); %Generate the new name for saving
savename =string(regexprep(name,'_oldname.set','_newname.mat'));
save(savename, '-struct', 'data');
end
The code doesn’t give any error. However, it doesn’t run as I expected.
‘data2’ still contains 26 fields, but only the last field contains 1 structure corresponding to the participant. The other fields contain 1x30 cell.
I guess it is because every time I run the loop it overwrites the previous fields, leaving only the last field correct. So, I think I might need a temporary variable where to store each iteration of the loop.
I thought to create as the temporary storage for each field
structure = [];
namelist = {‘A’;’B’;’C’;’D’;’E’;’F’;’G’;’H’;’I’;’J’;’K’;’L’;’M’;’N’;’O’;’P’;’Q’;’R’;’S’;’T’;’U’;’V’;’W’;’X’;’Y’;’Z’};
for i = 1:length(namelist)
structure.(namelist{i})={};
end
But cannot figure out how to make it work.
You need to take the line data2 = data; out of the for loops.
Antoine T is right, you always copy the original structure data again to data2 in every loop. That is why it won't get changed (except for the very last step of the loop, where you add a single field name to it.)
Regarding your other problem:
% create empty struct:
S = struct();
% loop
for i = 1:25
% create field name
nm = char( double('A') +i );
% create new field with empty cell.
S.(nm) = {};
end
It is just nice to convert number to chars as fieldnames. Your primary error was that you used the wrong inverted comma to create chars.
A minor flaw though was that you allocated strucutre = [] as an empty matrix rather than as an empty struct

How do I find out in which strucutre my matlab variable is stored in?

I have raw data in a .mat format. The Data is comprised of a bunch of Structures titled 'TimeGroup_XX' where xx is just a random number. Each one of these structures contains a bunch of signals and their corresponding time steps.
It looks something like this
TimeGroup_45 =
time45: [34069x1 double]
Current_Shunt_5: [34069x1 double]
Voltage_Load_5: [34069x1 double]
This is simply unusable, as I simply do not know where the variable I am looking for is hiding in 100's of the structures contained in the raw data. I just know that I am looking for 'Current_Shut_3' for example!
There has to be a way that would allow me to do the following
for all variables in Work space
I_S3 = Find(Current_Shut_3)
end for
Basically I do not want to manually click through every structure to find my variable and just want it to be saved in a normal time series instead of it being hidden in a random structure! Any suggestion on how to do it? There has to be a way!
I have tried using the 'whos' command, but did not get far, as it only returns a list of the stored strucutres in the workspace. I cannot convert that text to a variable and tell it to search for all the fields.
Thanks guys/girls!
This is a great example of why you shouldn't iterate variable names when there are plenty of adequate storage methods that don't require code gymnastics to get data back out of. If you can change this, do that and don't even bother reading the rest of this answer.
Since everything is apparently contained in one *.mat file, specify an output to load so it's output into a unified structure and use fieldnames to iterate.
Using the following data set, for example:
a1.Current_Shunt_1 = 1;
a2.Current_Shunt_2 = 2;
a5.Current_Shunt_5 = 5;
b1.Current_Shunt_5 = 10;
save('test.mat')
We can do:
% Load data
alldata = load('test.mat');
% Get all structure names
datastructs = fieldnames(alldata);
% Filter out all but aXX structures and iterate through
adata = regexpi(datastructs, 'a\d+', 'Match');
adata = [adata{:}];
queryfield = 'Current_Shunt_5';
querydata = [];
for ii = 1:numel(adata)
tmp = fieldnames(alldata.(adata{ii}));
% See if our query field is present
% If yes, output & break out of loop
test = intersect(queryfield, tmp);
if ~isempty(test)
querydata = alldata.(adata{ii}).(queryfield);
break
end
end
which gives us:
>> querydata
querydata =
5

Naming Image using index of for loop in each iteration

I am working in MATLAB for my image processing project.
I am using a for loop to generate some kind of image data (size of image varies) with each loop iteration. My problem is how do stop it from overwriting the image in next iteration.
Img(i,j)=data
Ideally I would like it to have
Img_1 = data (for 1st iteration)
Img_2 = data (for 2nd iteration)
Img_3 = data (for 3rd iteration)
and so on...
Is there any way, it can be acheived?
Yes, you can use dynamic field names with structures. I wouldn't recommend using separate variable names because your workspace will become unwieldy. Do something like this:
img_struct = struct(); %// Create empty structure
for ii = 1 : num_iterations
%// Do your processing on data
%...
%...
img_struct.(['Img_' num2str(ii)]) = data; %// After iteration
end
This will create a structure called img_struct where it will have fields that are named Img_1, Img_2, etc. To access a particular data from an iteration... say... iteration 1, do:
data = img_struct.Img_1;
Change the _1 to whatever iteration you choose.
Alternatively, you can use cell arrays... same line of thinking:
%// Create empty cell array
img_cell = cell(num_iterations, 1);
for ii = 1 : num_iterations
%// Do your processing on data
%...
%...
img_cell{ii} = data; %// After iteration
end
Cell arrays are arrays that take on any type per element - or they're non-homogeneous arrays. This means that each element can be whatever you want. As such, because your image data varies in size at each iteration, this will do very nicely. To access data at any iteration, simply do:
data = img_cell{ii};
ii is the index of the iteration you want to access.
If you want to literally obtain what you are asking for, you can use the eval() function, which takes a string as input that it will evaluate as if it were a line of code. Example:
for i=1:3
data=ones(i); % assign data, 'ones(i)' used as dummy for test
eval(['Img_' num2str(i) '=data;'])
end
However, I would recommend using cell arrays {}, or alternatively the struct function that rayryeng both suggested.

Extracting a matrix of data from a matrix of structs

I have a matrix of structs. I'm trying to extract from that matrix a matrix the same size
with only one of the fields as values.
I've been trying to use struct2cell and similar functions without success.
How can this be done?
If I understand you correctly, you have an array of struct like e.g this
s(1:2,1:3) = struct('a',1,'b',2);
Now you want a different struct that only has the field b
[newS(1:2,1:3).b] = deal(s.b);
edit
If all you need is the output (and if the field values are scalar), you can do the following:
out = zeros(size(s));
out(:) = cat(1,s.b)
I'll borrow Jonas' example. You can use the [] to gather a particular field.
% Create structure array
s(1:2,1:3) = struct('a',1,'b',2);
% Change values
for idx = 1:prod(size(s))
s(idx).a = idx;
s(idx).b = idx^2;
end
% Gather a specific field and reshape it to the size of the original matrix
A = reshape([s.a],size(s));
B = reshape([s.b],size(s));
I have a similar problem, but the contents of the field in my structure array are varying length strings that I use to tag my data, so when I extract the contents of the field, I want a cell of varying length strings.
This code using getfield and arrayfun does the job, but I think it is more complicated than it needs to be.
sa = struct('name', {'ben' 'frank', 'betty', 'cybil', 'jack'}, 'value', {1 1 2 3 5})
names = arrayfun(#(x) getfield(x, 'name'), sa, 'UniformOutput', false)
Can anyone suggest cleaner alternative? extractfield in the mapping toolbox seems to do the job, but it is not part of the base MATLAB system.
Update: I have answered my own embedded question.
names = {sa.name}

Create an array of 'Geostruct' Data in Matlab

Right now I am creating mapstructs in Matlab and then exporting them individually as shape files using the shapewrite() function.
However, instead of exporting them individually I want to store all of them into an array and then save it at the end as one single shapefile which holds all of the points from the mapstructs stored in the array.
My problem is I don't know how to initialize an array to hold these mapstructs. I've tried
`a = struct(sizeofarray)`
but it isn't compatible with mapstructs. I would appreciate any help!
You can store any kind of data in a cell array:
a = cell(sizeofarray,1);
You can then assign them like this:
a{1} = firstmapstruct;
a{2} = secondmapstruct;
However, if I understand you correctly you have mapstructs from the MATLAB Mapping Toolbox and want to concat structs of this form:
firstmapstruct =
609x1 struct array with fields:
Geometry
BoundingBox
X
Y
STREETNAME
RT_NUMBER
CLASS
ADMIN_TYPE
LENGTH
So you should probably do
a = firstmapstruct;
a(end+1:end+numel(secondmapstruct))= secondmapstruct;
and so on...
If all of your individual mapstructs have the same fields, you should be able to initialize a structure array by replicating one of your mapstructs using the function REPMAT:
a = repmat(mapstruct1,1,N); %# A 1-by-N structure array
Then just fill in each element as needed:
a(2) = mapstruct2; %# Assign another mapstruct to the second array element
a(3).X = ...; %# Assign a value to the X field of the third element
a(3).Y = ...; %# Assign a value to the Y field of the third element
You can find out more information about Geographic Data Structures in this documentation.