MATLAB Answers


How do I extract subset of all fields from structure?

Asked by Francesco Bussola on 16 Jun 2018
Latest activity Edited by IdealGas on 11 Nov 2019 at 4:32
Accepted Answer by Jan
I have my data stored in a structure. Every field is a 11300x1 array of doubles. I want to extract all (also some would be interesting) data that meet a certain condition to a new struct built the same way of the first:
e.g.: if field1 is 'time', field2 is 'temperature' and field3 is 'length' I want to extract all of the triples (time, temperature, length) that have a temperature > 300 K and save them contiguously in a new structure 'data_high_temperature'.


Sign in to comment.




2 Answers

Answer by Jan
on 16 Jun 2018
Edited by Jan
on 16 Jun 2018
 Accepted Answer

index = data.temperature > 300;
data2.time = data.time(index);
data2.temperature = data.temperature(index);
data2.length = data.length(index);
Maybe you want it more general:
function T = IndexedStructCopy(S, Condition, FieldList)
if nargin == 2
FieldList = fieldnames(S);
for iField = 1:numel(FieldList)
Field = FieldList{iFile};
T.(Field) = S.(Field)(Condition);
Call this like:
data2 = IndexedStructCopy(data, data.temperature > 300)
or perhaps:
data2 = IndexedStructCopy(data, data.temperature > 300, ...
{'time', 'temperature', 'length'})


Show 1 older comment
condition is not working.its stating too many aruguments
@ammu v: Please post your code and a copy of the complete error message.
@ammu v: The example does not work for all cases. Directly calling a field of a nonscalar structure array will end up with multiple returned values. The following modification should produce a proper condition (assuming elements in temperature are 1x1 numeric).
data2 = IndexedStructCopy(data, [data.temperature] > 300)
A safer way is feeding logical or location arrays to the condition argument.

Sign in to comment.

Answer by Image Analyst
on 16 Jun 2018

Try this (untested):
% Extract fields into single vectors
temps = [str.temperature]
times = [str.time]
lengths = [str.length]
% Find elements meeting criteria
highTempIndexes = temps > 300;
% Assign field to be only those elements meeting criteria.
str.time = times(highTempIndexes);
str.temperature = temps(highTempIndexes);
str.length= lengths(highTempIndexes);


Sign in to comment.