How to create groups by using labels?

1 回表示 (過去 30 日間)
Jim
Jim 2019 年 10 月 4 日
コメント済み: Daniel M 2019 年 10 月 8 日
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 件のコメント
Jim
Jim 2019 年 10 月 4 日
Thank you very much!

サインインしてコメントする。

その他の回答 (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 Center および File ExchangeAxis Labels についてさらに検索

タグ

製品


リリース

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by