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

 Respuesta aceptada

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...

Más respuestas (0)

Categorías

Más información sobre Mathematics en Centro de ayuda y File Exchange.

Productos

Preguntada:

el 13 de Mzo. de 2019

Comentada:

el 13 de Mzo. de 2019

Community Treasure Hunt

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

Start Hunting!

Translated by