# How to attribute a letter to unique combinaisons

1 view (last 30 days)
012786534 on 17 Sep 2020
Commented: 012786534 on 17 Sep 2020
Hi,
I have a very simple question that is a bit tricky to explain: I have a table like this
var_a = {'T1','T1','T1','T1','T1','T1','T2','T2','T2','T2','T2','T2','T2','T2'}';
var_b = [2,2,2,2,3,3,8,8,8,9,9,10,10,11]';
t = table(var_a, var_b)
and for every unique var_a id, I want every unique combinaison between var_a and var_b to be attributed a different letter beginning with 'A'. In other words the desired output would looks like this:
var_a = {'T1','T1','T1','T1','T1','T1','T2','T2','T2','T2','T2','T2','T2','T2'}';
var_b = [2,2,2,2,3,3,8,8,8,9,9,10,10,11]';
var_c = {'A', 'A', 'A', 'A', 'B', 'B', 'A', 'A', 'A', 'B', 'B', 'C', 'C', 'D'}';
desired_out_put = table(var_a, var_b, var_c)
Thank you,

Stephen Cobeldick on 17 Sep 2020
Edited: Stephen Cobeldick on 17 Sep 2020
There does not seem to be a convenient way to apply a function to table groups that does not also accumulate the results (e.g. like splitapply does). Here is one workaround:
>> A = {'T1';'T1';'T1';'T1';'T1';'T1';'T2';'T2';'T2';'T2';'T2';'T2';'T2';'T2'};
>> B = [2;2;2;2;3;3;8;8;8;9;9;10;10;11];
>> T = table(A,B)
T =
A B
____ __
'T1' 2
'T1' 2
'T1' 2
'T1' 2
'T1' 3
'T1' 3
'T2' 8
'T2' 8
'T2' 8
'T2' 9
'T2' 9
'T2' 10
'T2' 10
'T2' 11
>> G = findgroups(T.A);
>> F = @(b) {num2cell(char('A'+cumsum([0;diff(b)~=0])))};
>> Y = splitapply(F,T.B,G);
>> T.C = cell(height(T),1); % preallocate
>> for k = 1:max(G), T{G==k,'C'} = Y{k}; end
>> T
T =
A B C
____ __ ___
'T1' 2 'A'
'T1' 2 'A'
'T1' 2 'A'
'T1' 2 'A'
'T1' 3 'B'
'T1' 3 'B'
'T2' 8 'A'
'T2' 8 'A'
'T2' 8 'A'
'T2' 9 'B'
'T2' 9 'B'
'T2' 10 'C'
'T2' 10 'C'
'T2' 11 'D'

#### 1 Comment

012786534 on 17 Sep 2020