MATLAB: Extract some data from a structure and create a new structure.

extract datastructures

This is really a follow on to a previous question I asked. I'm given a structure of arrays. The following is an example of this structure.
data.Sen = {'U1'; 'U2'; 'U1'; 'U1'}
data.Tid = {'1'; '1'; '1';'2'}
data.Obj = {'U1_1';'U2_1';'U1_2';U1_1'}
data.X = {'10'; '5'; '3'; '1'}
data.Y = {'20'; '7'; '4'; '2'}
I have brute forced getting the data I want with:
senidx = strcmp(data.Sen,'U1');
thesen = data.Sen(senidx)
theX = data.X(senidx)
theY = data.Y(senidx)
theTid = data.TID(senidx)
but what I think I want to do is something like this:
for nField = 1:numel(myfieldnames)
mField = myfieldnames{nField}
mydata.(mField) = data.(mField)(strcmp(data.Sen_T,'U1'))
end
But this results in the following error: "Struct contents reference from a non-struct array object."

Best Answer

This should work:
senidx = strcmp(data.Sen, 'U1');
mydata = structfun(@(fv) fv(senidx), data, 'UniformOutput', false);