How can I concatenate vectors based on a grouping label contained by a separate variable?
조회 수: 1 (최근 30일)
이전 댓글 표시
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
채택된 답변
Stephen23
2021년 6월 4일
편집: Stephen23
2021년 6월 4일
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}
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!