How to create groups by using labels?
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Akzeptierte Antwort
the cyclist
am 4 Okt. 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.
Weitere Antworten (1)
Daniel M
am 4 Okt. 2019
Bearbeitet: Daniel M
am 4 Okt. 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 Kommentare
Daniel M
am 8 Okt. 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'}
Siehe auch
Kategorien
Mehr zu Axis Labels finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!