Obtaining the index of elements that belong to group
8 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Adam Danz
2020-9-8
编辑:Adam Danz
2020-9-8
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Call Python from MATLAB 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!