skyisfalling
skyisfalling

Reputation: 53

Removing certain elements from an array that fit a condition

How to remove elements from an array that have difference of 3 or less between subsequent elements? For example

A=[3 6 10 14 17 20]

to this

B=[3 10 14 20]

I believe I can use diff but in what context should I use it to achieve this?

Upvotes: 1

Views: 85

Answers (1)

Suever
Suever

Reputation: 65430

You can use diff and then compare this to 3. You can then construct a logical array (that includes the first value by default) and use this to index into A.

tokeep = [true, diff(A) > 3];
B = A(tokeep);

In your example though, the difference between 17 and 20 is 3 so that would remove 20.

Upvotes: 3

Related Questions