user679460
user679460

Reputation: 191

matlab search a matching element

I have an integer array of length 2000 elements. For ex

x = [2, 4, 5, 6, 5,6,7,5......];

Now in this array i need to find an element which occurs repeatedly. For ex I need to know how many times a number '5' has been occurred. In the above example it is three times.

Is there any way to search an matching element and returns the count in matlab?

Upvotes: 1

Views: 840

Answers (2)

Prashant Kumar
Prashant Kumar

Reputation: 22539

A quick way get the count is

sum(x == 5)

If you need the indicies of the matching elements:

find(x == 5)

Notice, the count is also length(find(x == 5)). Standard caveats apply toward the use of == and floating point numbers.

Upvotes: 2

mathematical.coffee
mathematical.coffee

Reputation: 56915

Do you know the number in advance?

If so, to work out how many times it appears in x you could do:

sum(x==5)

The x==5 creates a vector of [FALSE FALSE TRUE FALSE TRUE FALSE FALSE TRUE ...], being TRUE whenever x is 5.

The sum then adds up that vector, where FALSE maps to 0 and TRUE to 1.

Upvotes: 2

Related Questions