If the second column is sorted (as in your example):
m([true; diff(m(:,2))~=0],1)
Frage
I have matrices of this kind:
m = [randi(20,1,20)', [ones(1,3), ones(1,5)*2, ones(1,8)*3, ones(1,4)*4]']
ans =
5 1
19 1
6 1
16 2
4 2
6 2
2 2
12 2
14 3
11 3
9 3
13 3
13 3
14 3
13 3
19 3
5 4
15 4
5 4
3 4
Is there an efficient way to extract the values of m(:,1)
that correspond to the first occurrence of each number of m(:,2)
?
In my example that would be:
ans =
5 16 14 5
Lösung
If the second column is sorted (as in your example):
m([true; diff(m(:,2))~=0],1)
Andere Tipps
Divakar is a boss! In any case, you can use the unique
function on the second column of your matrix that will tell you where the first occurrence is of the number you want. Try doing this:
[~,index] = unique(m(:,2));
The first output parameter will be an array that eliminates all of the duplicates in m(:,2)
, while index
will tell you where the first occurrence of every unique element occurred. We don't need the first parameter, which is why we have nulled it with ~
.
As such, index
should thus be:
index =
1
4
9
17
Then you can access your values via: m(index,1)
, which should thus give you:
5
16
14
5
Well I felt like jumping in here and I had to come up with something, so here it is.
Code
binmat1 = bsxfun(@eq,m(:,2),min(m(:,2)):max(m(:,2)))
[~,ind] = max(binmat1(:,any(binmat1)))
out = m(ind)