MATLAB: Not sure how to ask this, but here’s the scenario:

combinationspermutations

Ok, i'm not sure what this transformation is called, but here's what i want to do.
Given a matrix of categorical variables:
x = ['a', 'b';
'a', 'c';
'a', 'b';
'b', 'c';
'c', 'a';
'a', 'd' ]
Generate a matrix that has all of the combination counts:
a b c d
- - - -
a | 0 2 1 1
b | 0 0 1 0
c | 1 0 0 0
d | 0 0 0 0
Any thoughts?

Best Answer

%%Data
x = {'a', 'b';
'a', 'c';
'a', 'b';
'b', 'c';
'c', 'a';
'a', 'd'};
%%Engine
uv = unique(x(:));
[~,idx] = ismember(x,uv);
m = accumarray(idx,1,numel(uv)+[0 0]);
%%Formatting
T = array2table(m,'VariableNames',uv,'RowNames',uv)
Results:
T =
a b c d
_ _ _ _
a 0 2 1 1
b 0 0 1 0
c 1 0 0 0
d 0 0 0 0