1

我有一个如下表T

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 

我需要索引它memberIdproductId所以结果是:

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

1 回答 1

1

您可以使用分类数组和结构来执行此操作:

% 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))

要获得输出 ( s):

A: {'xd'  'z'}
B: {'w'  'x'  'y'  'z'}
C: {'wh'  'x'}
D: {'w'  'z'}
于 2016-08-10T13:09:54.527 回答