Jose Ramon
Jose Ramon

Reputation: 5444

Calculate the co-occurrence of a vector

I am trying to calculate the co-occurrence of some values in a vector in Matlab. I am using the following code to do so:

x = graph(:,1);
y = zeros(size(x));
for i = 1:length(x)
   y(i) = sum(x==x(i));
end

The above code calculates the co-occurrence of every index inside the vector. I want to have the co-occurrence of the unique indexes. How can I do so?

I found the following implementation:

a = unique(x);
out = [a,histc(x(:),a)];

However, I want the indexes to be as it is, without sorting.

Upvotes: 1

Views: 93

Answers (1)

McMa
McMa

Reputation: 1566

Let's see if this is what you need:

a=unique(x);
Coocurrence=zeros(length(a));

for ii=1:length(a)

    Coocurrence(ii)=sum(x==a(ii));

end

or the vectorized solution

a=unique(x);
Coocurrence=sum(bsxfun(@eq,x,a'),2);

Upvotes: 4

Related Questions