carloscc
carloscc

Reputation: 799

Filter Multiple Conditions Array

I am trying to filter every negative number as well as every other number on an array with MATLAB. How's this possible? I thought I could have done this but it is not working:

Z = A(A<0 | 2:2:end)

Upvotes: 1

Views: 124

Answers (1)

Suever
Suever

Reputation: 65430

The issue is that 2:2:end simply returns the following array

[2, 4, 6, .... % All the way up to numel(A)

The conditional yields a logical array the size of A that is true where an element is negative and false otherwise.

You can't combine these two because they are two different types and two different sizes.

If you want all numbers that are either a negative number or occur at an even location you could create a logical array that is true at all of the even locations (and false otherwise) and then perform logical operations using that instead. To do this, we create an array from [1....numel(A)] and perform the modulo operation (mod) with 2. Even numbers will have a remainder of 0 and odd numbers will have a remained of 1. Therefore, by comparing the result of mod(...,2) to 0 (== 0) we get a logical array that is true in all of the even locations and false otherwise.

even_locations = mod(1:numel(A), 2) == 0;
Z = A(A < 0 | even_locations);

If you simply want the even locations that are also negative

tmp = A(2:2:end);
Z = tmp(tmp < 0);

Or you can use the even_locations array above:

Z = A(A < 0 & even_locations);

Upvotes: 1

Related Questions