user3371528
user3371528

Reputation: 75

Filter out combinations in Matlab

Currently I can generate all the combinations from categories alpha, beta, gamma and delta (1 1 1 1, 1 1 1 2 etc.).

Current code:

alpha = [1, 2, 3];
beta  = [1, 2, 3, 4, 5];
gamma = [1, 2, 3, 4, 5];
delta = [1, 2, 3];
[a, b, c, d] = ndgrid (alpha, beta, gamma, delta);
combination = [a(:), b(:), c(:), d(:)];

I want to filter out some of those combinations i.e. get rid of any of the combinations where alpha is 1 and gamma is 4 etc.

How would I approach this?

Upvotes: 1

Views: 46

Answers (2)

Ian Riley
Ian Riley

Reputation: 523

What you're looking for is logical indexing

c1 = (combination(:,1) ~= 1); %rows where alpha is not 1
c2 = (combination(:,3) ~= 4); %rows where gamma is not 4

desired = combination(c1&c2,:); %output rows where both c1 and c2 are true

Upvotes: 2

Tasos Papastylianou
Tasos Papastylianou

Reputation: 22245

Ian Riley's answer has provided the correct approach if you want to create a new array from that information. Just adding to his answer that you can also use the same approach to remove the unwanted rows directly, by setting them to empty, i.e.:

>> combination(combination(:,1) == 1,:) = [];
>> combination(combination(:,3) == 4,:) = [];

Upvotes: 1

Related Questions