How to create groups by using labels?
13 views (last 30 days)
Show older comments
I have two arrays, one with values and one with labels, both of the same length.
For example :
V = [ 1 2 3 4 5 6 7 8]
L = { 'A', 'A', 'A', 'C', 'C', 'C', 'A', 'B' }
now I want to use to labels to split V into three groups like:
A = [1 2 3 7]
B = [8]
C = [4 5 6]
How do I do that? Cant find it anywhere
0 Comments
Accepted Answer
the cyclist
on 4 Oct 2019
Here is one way:
V = [ 1 2 3 4 5 6 7 8];
L = { 'A', 'A', 'A', 'C', 'C', 'C', 'A', 'B' };
[tf,loc] = ismember(L,unique(L));
for ni = 1:max(loc)
VV{ni} = V(loc==ni)
end
Note that I used a cell array to store the output, rather than the alphabetic sequence variables.
More Answers (1)
Daniel M
on 4 Oct 2019
Edited: Daniel M
on 4 Oct 2019
I don't recommend making variables dynamically for various reasons, but making a struct is fine to do, and can even make fieldnames dynamically:
[uL,~,iL] = unique(L);
for f = 1:length(uL)
s.(uL{f}) = V(iL==f);
end
The output struct s will have fieldnames that are the same as the labels in L.
3 Comments
Daniel M
on 8 Oct 2019
Well, how would you have done it manually? In your original post you wanted to make variables named A = [1 2 3 7], etc. How would you have done it if the label was a number instead?
You can try prepending a letter before any labels that start with numbers.
L = {'A','A','B','2','C','1','x1','1x'}
s = ~cellfun(@isempty, regexp(L,'^\d'),'UniformOutput',true) % finds the labels that start with a number
L(s) = cellfun(@(x) ['n',x],L(s),'UniformOutput',false); % preprend with the letter n
L
with output
L =
1×8 cell array
{'A'} {'A'} {'B'} {'2'} {'C'} {'1'} {'x1'} {'1x'}
s =
1×8 logical array
0 0 0 1 0 1 0 1
L =
1×8 cell array
{'A'} {'A'} {'B'} {'n2'} {'C'} {'n1'} {'x1'} {'n1x'}
See Also
Categories
Find more on Structures 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!