Obtaining the index of elements that belong to group
10 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
NA
el 8 de Sept. de 2020
Comentada: Adam Danz
el 9 de Sept. de 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
0 comentarios
Respuesta aceptada
Adam Danz
el 8 de Sept. de 2020
Editada: Adam Danz
el 8 de Sept. de 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
5 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Scope Variables and Generate Names en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!