How can I concatenate vectors based on a grouping label contained by a separate variable?
1 view (last 30 days)
Show older comments
Rafael Cordero
on 4 Jun 2021
Commented: Rafael Cordero
on 4 Jun 2021
Hello all,
I have 16 test subjects. Each subject underwent a different number of tests. For each test, I have a results vector. I would like to concatenate all the results vectors of the same subject.
Let met illustrate this with psuedo code.
Imagine I have the following test labels as strings, and in a separate variable, I have their test results vectors, each of which may be of different length. The indices of these two seperate variables match up, so that the nth test label corresponds to the nth results vector:
Test labels Results vector
'charlie_test_a' [54 (real) element vector]
'charlie_test_b' [59 (real) element vector]
'charlie_test_c' [23 (real) element vector]
'jane_test_a' [24 (real) element vector]
'jane_test_b' [21 (real) element vector]
'mildred_test_a' [119 (real) element vector]
'mildred_test_b' [ 89 (real) element vector]
'mildred_test_c' [24 (real) element vector]
'pelagius_test_a' [314(real) element vector]
...
What I would like, is to concatenate the results vector of each subject so that I would get something (e.g. a struct concat_results) like
concat_results.charlie = [136 (real) element vector]
concat_results.jane = [45 (real) element vector]
concat_results.mildred = [232 (real) element vector]
Is there an intelligent/fast way to perform this grouped concatenation?
Thank you!
0 Comments
Accepted Answer
Stephen23
on 4 Jun 2021
Edited: Stephen23
on 4 Jun 2021
N = ["charlie_test_a";"charlie_test_b";"charlie_test_c";"jane_test_a";"jane_test_b";"mildred_test_a";"mildred_test_b";"mildred_test_c";"pelagius_test_a"]
D = {rand(1,54);rand(1,59);rand(1,23);rand(1,24);rand(1,21);rand(1,119);rand(1,89);rand(1,24);rand(1,314)};
The old-fashioned way:
[U,X,Y] = unique(extractBefore(N,"_"));
F = @(n)horzcat(D{Y==n});
C = arrayfun(F,1:max(Y),'uni',0);
S = cell2struct(C,U,2)
Or using a table... not sure if this is much better:
T = table(N,D);
T.N = extractBefore(T.N,'_');
T = unstack(T, "D", "N", 'AggregationFunction',@(c){horzcat(c{:})});
T.charlie{1}
T.jane{1}
More Answers (0)
See Also
Categories
Find more on Hypothesis Tests in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!