2

Suppose I have a struct array in MATLAB:

a= struct('a1',{1,2,3},'a2',{4,5,6})

How can I efficiently (i.e. with vectorized code) filter the elements of the struct so that they satisfy some boolean property?

For instance:

  1. How would I create a new struct array b whose elements are the subset of a where both a1 is a multiple of 3 and a2 is a multiple of 3? The expected result is a struct array of size 1 with the element struct('a1', 3, 'a2', 6).
  2. How would I create a new struct array b whose elements are the subset of a where a1 is odd or a2 is a multiple of 3? The expected result is the following struct array of size 2: struct('a1', {1,3}, 'a2', {4,6}).

1 Answer 1

3

You can solve this problem with the mod(...) function and proper use of brackets and referencing. Consider

  1. Mod(x,3) will return zero if your number is a multiple of 3. mod(x,2) will return 1 if x is odd.
  2. You can get all your a1 or a2 values in a vector by typing [a.a1]. Just typing a.a1 gives a mess.
  3. You can filter our from your a structure by writing a = a([1 3]); or by writing a = a(logical([1 0 1])) to get the same result.
  4. You can use the & for logical and and | for logical or (see here).

Altogether, the following code solves your problem:

%% Part 1:
a= struct('a1',{1,2,3},'a2',{4,5,6});
logForA1isMod3 = (mod([a.a1], 3) == 0);
logForA2isMod3 = (mod([a.a2], 3) == 0);

a = a(logForA1isMod3  & logForA2isMod3);

%% Part 2:
a= struct('a1',{1,2,3},'a2',{4,5,6});
logForA1isOdd = (mod([a.a1], 2) == 1);

a = a(logForA1isOdd | logForA2isMod3);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.