MATLAB: How to extract subset of all fields from structure

extractMATLABstructuresubset

Hello,
I have my data stored in a structure. Every field is a 11300×1 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'.

Best 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);
end
for iField = 1:numel(FieldList)
Field = FieldList{iFile};
T.(Field) = S.(Field)(Condition);
end
end
Call this like:
data2 = IndexedStructCopy(data, data.temperature > 300)
or perhaps:
data2 = IndexedStructCopy(data, data.temperature > 300, ...
{'time', 'temperature', 'length'})