How can I randomly pick a row (A) from a matrix give the same value from array (B)?

I have a coordinate matrix (A) which is nx2, and an index array (B) which is nx1. for example:
A=[1,2; 0,3; 3,8; 6,5; ....; 3,7];
B=[1;2;2;3;1;1;3;...3; 2];
I want to randomly pick a row from A which has the same value group from B. for example:
G1=random a row [Ax1, Ay1; such that B=1];
G2=random a row [Ax2, Ay2; such that B=2];
G3=random a row [Ax3, Ay3; such that B=3]; and so on
G1,G2 ... are 1x2 corrdinate arrays.
Is there a command or simple algorithm to do the reandom assigmenet

 Réponse acceptée

If I understood correctly:
[~, ~, uid] = unique(B); %If B is an array of integers from 1 with no gaps, then uid will be the same as B and this line is not needed
result = splitapply(@(rows) A(rows(randi(numel(rows))), :), (1:size(A, 1))', uid)
result(1, :) will be a random row of A for which the uid of the B values is 1
result(2, :) will be a random row of A for which the uid of the B values is 2
etc...

Plus de réponses (0)

Catégories

En savoir plus sur Mathematics dans Centre d'aide et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by