Filter löschen
Filter löschen

How do I return the indices of randomly sampled matrices?

9 Ansichten (letzte 30 Tage)
virkuz000
virkuz000 am 29 Mai 2018
Kommentiert: virkuz000 am 5 Jun. 2018
Hello. I have two large matrices of equal size. I'm currently using randsample to put randomly selected values of one of the matrices into a new vector. But now I need to also identify the indices of the randomly selected values from the one matrix and correspond it to the same indices in the other matrix.
For example:
A = [1 2 3 4 5; 6 7 8 9 10; 11 12 13 14 15]
B = [16 17 18 19 20; 21 22 23 24 25; 26 27 28 29 30]
If I randomly select from A:
Arand = [3 6 10 1 15 11]
How do I get:
Brand = [18 21 25 16 30 26] where the values of Brand have the same indices in B as Arand has in A?
Do I need to abandon my use of randsample altogether?
Thanks for your help!

Akzeptierte Antwort

Jeff Miller
Jeff Miller am 30 Mai 2018
Especially if A has duplicated scores, it might be better to randomly sample the positions and then take elements of both arrays from those random positions:
nelements = numel(A);
SampleSize = 3;
randices = randsample(1:nelements,SampleSize,false);
randAs = A(randices)
randBs = B(randices)

Weitere Antworten (1)

Paolo
Paolo am 29 Mai 2018
Bearbeitet: Paolo am 29 Mai 2018
The following code uses find to search for Arand elements in matrix A, and arrayfun to apply the search for every element in Arand.
The indexes are then used to get the corresponding data from the B matrix.
%Your inputs.
A = [1 2 3 4 5; 6 7 8 9 10; 11 12 13 14 15];
B = [16 17 18 19 20; 21 22 23 24 25; 26 27 28 29 30];
%Your random sequence.
Arand = [3 6 10 1 15 11];
%Get index of position of elements Arand with respect to A.
index = arrayfun(@(x) find(A==x),Arand);
%Get B elements at positions specified by index.
Brand = B(index);
Output of Brand =
Brand = 18 21 25 16 30 26
  1 Kommentar
virkuz000
virkuz000 am 5 Jun. 2018
Thanks for answering! Your answer does answer the question I ask, but looking at Jeff's, I think his better applies to my project. But thanks again!

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Produkte


Version

R2015b

Community Treasure Hunt

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

Start Hunting!

Translated by