Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MATLAB: Fastest Way to Count Unique # of 2 Number Combinations in a Vector of Integers

Tags:

matlab

Given a vector of integers such as:

X = [1 2 3 4 5 1 2]

I would like to find a really fast way to count the number of unique combinations with 2-elements.

In this case the two-number combinations are:

[1 2] (occurs twice)
[2 3] (occurs once) 
[3 4] (occurs once) 
[4 5] (occurs once) 
[5 1] (occurs once) 

As it stands, I am currently doing this in MATLAB as follows

X = [1 2 3 4 5 1 2];
N = length(X)
X_max = max(X);
COUNTS = nan(X_max); %store as a X_max x X_max matrix

for i = 1:X_max

    first_number_indices   = find(X==1)
    second_number_indices = first_number_indices + 1;
    second_number_indices(second_number_indices>N) = [] %just in case last entry = 1
    second_number_vals = X(second_number_indices);

   for j = 1:X_max
        COUNTS(i,j) = sum(second_number_vals==j)
   end
end

Is there a faster/smarter way of doing this?

like image 716
Berk U. Avatar asked May 08 '13 04:05

Berk U.


People also ask

How do I count unique values in MATLAB?

Count of Unique ElementsFind the unique elements in a vector and then use accumarray to count the number of times each unique element appears. Create a vector of random integers from 1 through 5. a = randi([1 5],200,1); Find the unique elements in the vector.

What does Accumarray do in MATLAB?

The MATLAB function accumarray seems to be under-appreciated. accumarray allows you to aggregate items in an array in the way that you specify.

How do you count the number of elements in an array in MATLAB?

n = numel( A ) returns the number of elements, n , in array A , equivalent to prod(size(A)) .

How do you arrange an array in ascending order in MATLAB?

B = sort( A ) sorts the elements of A in ascending order. If A is a vector, then sort(A) sorts the vector elements. If A is a matrix, then sort(A) treats the columns of A as vectors and sorts each column.


1 Answers

Here is a super fast way:

>> counts = sparse(x(1:end-1),x(2:end),1)
counts =
   (5,1)        1
   (1,2)        2
   (2,3)        1
   (3,4)        1
   (4,5)        1

You could convert to a full matrix simply as: full(counts)


Here is an equivalent solution using accumarray:

>> counts = accumarray([x(1:end-1);x(2:end)]', 1)
counts =
     0     2     0     0     0
     0     0     1     0     0
     0     0     0     1     0
     0     0     0     0     1
     1     0     0     0     0
like image 119
Amro Avatar answered Sep 21 '22 00:09

Amro