MATLAB: Find unique numbers in a set

exerciseunique

This is, lol, I guess another personal exercise (sort of, although it is kind towards solving a bigger problem).
Anyway I'm having trouble figuring out how to find the unique numbers in an array/set.
Now, I KNOW about the unique function. It's cool. I'm even using it elsewhere. But I am also interested in how it is written, and the unique.m file in the matlab toolbox is basically incomprehensible to me.
So far I have started out really simple. What I am trying to do is simply look at an array, see if a number is repeated (literally true false atm), then stick that number and it's occurrence boolean into a cell. Here is the code so far:
%What we want to do is fill a cell as follows
%C=cell{1,2,N(=Unique values in [S])}
%Where
%C{1,1,N} = [N_unique] (N_unique => Nq)
%C{1,2,N} = [Occurence of N_unique] (=> On(Nq))
%Such that
%C{:,:,1} =

%[Nq(1)] [Oc(Nq(1))]
%...
%C{:,:,N} =
%[Nq(N)] [Oc(Nq(N))]
%
%This requires an index N that iterates only once for every number,
%whether or not it occurs more than once.
%This also requires another index Oc that iterates once for every time
%its respective number occurs. Oc must be at least one for every number.
%So, the array [267 308 267] should produce
%C{:,:,1} =
%[267] [2]
%C{:,:,2} =
%[308] [1]
A = [267 267 308];
N = 1; %Index for each unique number
On = 0;
for i = 1:length(A)
for j = 1:length(A)
if A(i) == A(j) && i~=j
%fprintf('%d %d %d %d %d\n', A(i),i, A(j),j,1);
%A(i) has occured more than once
On = 1; %True for On(A(i))
elseif A(i) ~= A(j)
fprintf('%d %d %d %d %d\n', A(i),i, A(j),j, 0);
%A(i) has not occured more than once
On = 0; %False for On(A(i))
end
C{1,1,N} = A(i);
C{1,2,N} = On;
end
end
Now this code is pretty unfinished, obviously. For example, N doesn't even increase. It just sits there the whole time at 1. This is because I can't figure out how to get it to iterate once PER NUMBER, as opposed to, for example, per loop.
Also Oc right now is just true/false, not the actual occurrence rate.
Anyway sorry for wasting time but I'm just really frustrated and curious about how to do this.

Best Answer

If I were writing a 'unique' function, the first operation would be to sort the set. There are many efficient routines to do that. After that it is a breeze picking out only those elements in the sorted sequence that are unique: pick the first (or last) of each consecutive subsequence of equal elements.