# Obtaining the index of elements that belong to group

3 views (last 30 days)
NA on 8 Sep 2020
Commented: Adam Danz on 9 Sep 2020
I have 4 groups
A =[1;2;3];
B = [4;5];
C = [6;7];
D = [8,9];
I put all of these value together
all_val = [1;2;3;4;5;6;7;8;9];
From all_val I choose 2 elements.
idx = datasample(all_val, 2,'Replace',false);
I want to know the chosen idx is belong to which groups.
I do not know how to write this code.
Result should be something like:
i=1 i=2
third index of A first index of B
second index of c second index of D

Adam Danz on 8 Sep 2020
Edited: Adam Danz on 8 Sep 2020
See the second output of datasample to get the selected index.
The problem you're having is that you don't know which rows of all_val corresponds to which groups. When you create all_val you need to keep track of the group IDs.
Demo:
A =[1;2;3];
B = [4;5];
C = [6;7];
D = [8;9];
abcd = {A;B;C;D};
all_vals = cell2mat(abcd); % <-- Create all_vals this way
n = cellfun(@numel,abcd);
g = repelem(1:numel(abcd),1,n)';
g(:,2) = cell2mat(arrayfun(@(n){(1:n)'},n));
g is a nx2 grouping variable where the first column indicates which variable (A,B,C,D) each value in all_vals comes from. The second column indicates the index within that variable.
g =
1 1
1 2
1 3
2 1
2 2
3 1
3 2
4 1
4 2
This is where the 2nd output to datasample comes into play.
[y, idx] = datasample(all_val, 2,'Replace',false);
If idx is [2,8] then the selected variable comes from
g(idx,:)
% ans =
% 1 2 % 1st variable (A), 2nd row
% 4 1 % 4th variable (D), 1st row
NA on 9 Sep 2020
Thank you for your suggestion. I want to use them as labels.
Suppose I have the additional data.
e = [1,2; 2,3; 3,1];
v = (1:max(max(3)))';
%% first grouping
A =[1;2;3];
B = [4;5;6];
C = [7;8;9];
D = [10;11;12];
%% second grouping
los = {A;C};
def = {B;D};
Rest of the code
abcd = {A;B;C;D};
all_vals = cell2mat(abcd); % <-- Create all_vals this way
n = cellfun(@numel,abcd);
g = repelem({'A','B','C','D'},1,n)';
g(:,2) = repelem({'los','def','los','def'},1,n)';
I want to add another column to g like this
g =
12×3 cell array
{'A'} {'los'} {[1,2]}
{'A'} {'los'} {[2,3]}
{'A'} {'los'} {[3,1]}
{'B'} {'def'} {[1]}
{'B'} {'def'} {[2]}
{'B'} {'def'} {[3]}
{'C'} {'los'} {[1,2]}
{'C'} {'los'} {[2,3]}
{'C'} {'los'} {[2,3]}
{'D'} {'def'} {[1]}
{'D'} {'def'} {[2]}
{'D'} {'def'} {[3]}
I mean
first element of los should be ---> e(1)=(1,2)
second element of los should be ---> e(2)=(2,3)
third element of los should be ---> e(3)=(3,1)
first element of def should be ---> v(1)=1
second element of def should be ---> v(2)=2
third element of def should be ---> v(3)=3
I do not know how to relate e to los and v to def. How to change bellow code?
g(:,3) = num2cell(cell2mat(arrayfun(@(n){(1:n)'},n)));
Adam Danz on 9 Sep 2020
I don't understand