How to create groups by using labels?

10 vues (au cours des 30 derniers jours)
Jim
Jim le 4 Oct 2019
Commenté : Daniel M le 8 Oct 2019
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

Réponse acceptée

the cyclist
the cyclist le 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.
  1 commentaire
Jim
Jim le 4 Oct 2019
Thank you very much!

Connectez-vous pour commenter.

Plus de réponses (1)

Daniel M
Daniel M le 4 Oct 2019
Modifié(e) : Daniel M le 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 commentaires
Jim
Jim le 8 Oct 2019
This doesnt work if the labels are numbers.
Do you have any idea how to make it work for numberlabels aswell?
Daniel M
Daniel M le 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'}

Connectez-vous pour commenter.

Catégories

En savoir plus sur Structures dans Help Center et File Exchange

Produits


Version

R2019a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by