Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A question about matrix manipulation

Given a 1*N matrix or an array, how do I find the first 4 elements which have the same value and then store the index for those elements?

PS: I'm just curious. What if we want to find the first 4 elements whose value differences are within a certain range, say below 2? For example, M=[10,15,14.5,9,15.1,8.5,15.5,9.5], the elements I'm looking for will be 15,14.5,15.1,15.5 and the indices will be 2,3,5,7.

like image 644
view Avatar asked Jan 14 '11 10:01

view


1 Answers

If you want the first value present 4 times in the array 'tab' in Matlab, you can use

num_min = 4
val=NaN;
for i = tab
    if sum(tab==i) >= num_min
        val = i;
        break
    end
end
ind = find(tab==val, num_min);

By instance with

tab = [2 4 4 5 4 6 4 5 5 4 6 9 5 5]

you get

val =
     4
ind =
     2     3     5     7
like image 102
Clement J. Avatar answered Sep 24 '22 23:09

Clement J.