You can do this by combining unique
and histc
like this:
newmatrix = [unique(A); histc(A, unique(A))]
The unique
function returns a list of all the numbers in your vector, whereas histc
counts each occurrence of the unique value in the original vector.
Note that for large vectors, Luis' answer will be faster as it only calls unique
once. However, if you're one of those who prefer one-liners, this answer should do the trick.
If your vector might be either vertical or horizontal, you the above will result in a 2nx1
vector instead of a nx2
matrix. One possibility would be to call reshape
like this:
result = reshape([uA; histc(A, uA)],[],2);