Reputation: 31
I have a set of data looks like this:
data =
4 35
4 36
4 37
4 39
4 50
6 24
6 35
6 36
6 39
6 50
6 78
10 24
10 35
10 36
10 39
...
The actual matrix is in the order of 70000 X 2. What I want is to form a matrix containing all the unique data pair, so each element is not the same as the previous ones, would be look like
result =
4 35
6 24
10 36
I am think about a method like this
Step 1. find out all the index of unique column 1, in this case would be
index =
1
6
12
Step 2. Do a for-loop like this
result = data(index);
for j = 1:length(index)
if result(j,2) == result(j-1,2)
result(j) = data(index+1)
end
end
Here comes a problem, I have the possibility of getting some result like this
4 35
6 24
10 35
Then it is not unique. However, I don't want to write something like
if result(j,2) = result(j-1,2) ...
or result(j,2) = result(j-2,2) ...
or result(j,2) = result(j-3,2) ...
or result(j,2) = result(j-4,2) ...
result(j) = data(index+?)
that would be even more complicated.
Thank you very much for the help in advance.
Upvotes: 3
Views: 4151
Reputation: 31
Hey I just figure out how to do it :) Thank you all for help :)
for j = 1:500 % random number, big enough to find out all my pairs
k = 1;
while any(bsxfun(@eq, store, data(k,2))|bsxfun(@eq, store, data(k,1)))
k = k+1;
if k > length(data)-1, break, end
end
pair(j,:) = data(k,:);
store(2*j-1) = pair(j,1);
store(2*j) = pair(j,2);
fprintf('the loop we are at is %d \n',j);
end
Upvotes: 0
Reputation: 9864
This should work
I = true(size(data,1),1);
idx = [];
while any(I)
idx(end+1) = find(I,1,'first'); %#ok
I = I & all(~bsxfun(@eq, data, data(idx(end),:)),2);
end
result = data(idx,:);
Upvotes: 0
Reputation: 1832
try this:
unique(data,'rows')
C = unique(A,'rows') treats each row of A as a single entity and returns the unique rows of A. The rows of the matrix C are in sorted order. The 'rows' option does not support cell arrays.
Upvotes: 6