M.Patil
M.Patil

Reputation: 81

How to extract field based on field value

%Input structure
s.a=[1; 2; 1; 3; 4; 1; 2]
s.b=[4; 9; 7; 1; 0; 3; 8]
% output required
s.a=[1; 1; 1]
s.b=[4; 7; 3]

The actual structure contains many fields of long size. How to extract corresponding field values, when condition is put for field 'a' (when a==1).

Upvotes: 0

Views: 141

Answers (1)

Martin Seehafer
Martin Seehafer

Reputation: 156

Try this and adapt to the other fields:

s.b(s.a==1)

To do it for all fields in s except a and collect the results in a struct t you can use a loop:

t = struct()
fn = fieldnames(s);
for k=1:numel(fn)
    t.(fn{k}) = s.(fn{k})(s.a==1);
end

Upvotes: 3

Related Questions