How to create groups by using labels?

10 次查看(过去 30 天)
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

采纳的回答

the cyclist
the cyclist 2019-10-4
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 个)

Daniel M
Daniel M 2019-10-4
编辑:Daniel M 2019-10-4
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 个评论
Jim
Jim 2019-10-8
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 2019-10-8
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'}

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

标签

产品


版本

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by