Create an index to table

2019-07-25 07:46发布

问题:

I have a table T as below:

T = table({'A';'A';'B';'B';'B';'B';'C';'C';'D';'D'},...
          {'xd';'z';'x';'y';'z';'w';'x';'wh';'z';'w'},...
          [4;2;4;1;2;5;2;1;1;5], ...
          'VariableNames', {'memberId', 'productId','Rating'});
T = 
memberId    productId    Rating
________    _________    ______
'A'         'xd'         4     
'A'         'z'          2     
'B'         'x'          4     
'B'         'y'          1     
'B'         'z'          2     
'B'         'w'          5     
'C'         'x'          2     
'C'         'wh'         1     
'D'         'z'          1     
'D'         'w'          5 

I need to index it by memberId and productId so the result is:

A: {'xd'  'z'}
B: {'x'  'y' 'z' 'w'}
C: {'x' 'wh'}
.......

回答1:

You can use categorical arrays and a structure to do this:

% convert to categorical arrays
T.memberId = categorical(T.memberId);
T.productId = categorical(T.productId);
% cross-tabulate memberId vs. productId
cross_T = crosstab(T.memberId,T.productId);
% a function to return the productId for all 1 in row
productId = categories(T.productId).';
row = @(x) productId(logical(cross_T(x,:)));
% preform on all rows
rBy_c = arrayfun(row,1:size(cross_T,1),'UniformOutput',false).';
% convert to structure for readability
s = cell2struct(rBy_c,categories(T.memberId))

To get the output (s):

A: {'xd'  'z'}
B: {'w'  'x'  'y'  'z'}
C: {'wh'  'x'}
D: {'w'  'z'}