bonifaz
bonifaz

Reputation: 598

Creating Indicator matrix based on vector with group IDs

I have a vector of group IDs:

groups = [ 1 ; 1; 2; 2; 3];

which I want to use to create a matrix consisting of 1's in case the i-th and the j-th element are in the same group, and 0 otherwise. Currently I do this as follows:

n = size(groups, 1);
indMatrix = zeros(n,n);
for i = 1:n
    for j = 1:n
        indMatrix(i,j) = groups(i) == groups(j);
    end  
end
indMatrix

indMatrix =

 1     1     0     0     0
 1     1     0     0     0
 0     0     1     1     0
 0     0     1     1     0
 0     0     0     0     1

Is there a better solution avoiding the nasty double for-loop? Thanks!

Upvotes: 1

Views: 36

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112749

This can be done quite easily using implicit singleton expansion, for R2016b or later:

indMatrix = groups==groups.';

For MATLAB versions before R2016b you need bsxfun to achieve singleton expansion:

indMatrix = bsxfun(@eq, groups, groups.');

Upvotes: 2

Related Questions