user1723765
user1723765

Reputation: 6399

Sample from matrix and record matrix index in Matlab

I have a two column matrix of the following form:

 1.   1  1 
 2.   1  1
 3.   1  2
 4.   1  2
 5.   2  2
 6.   2  2
 7.   3  2
 8.   3  2
 9.   3  3 
 10.  4  3
 11.  4  4

I would like to sample a single number from the first column using say randsample().

Let's say the results is 2.

What I would like to know is which ROW was the sample taken from? (in this case it could have been sampled both from row 5 or row 6)

Is this possible?

Upvotes: 0

Views: 190

Answers (2)

Dennis Jaheruddin
Dennis Jaheruddin

Reputation: 21563

If you just need to sample one value, the solution as given by @igor milla is fine. But if you want to use the options given by randsample then I would recommend you to sample the column numbers rather than the sample directly.

A = rand(11,2); %suppose this is your matrix
k = 1; %This is the size of your desired sample
mysampleid = randsample(size(A,1),k)
mysample = A(mysampleid,:)

Now mysampleid contains the numbers of the columns, and mysample contains the rows that you sampled. If you just want to sample the first column you can use A(mysampleid,1) instead.

Upvotes: 0

Rody Oldenhuis
Rody Oldenhuis

Reputation: 38032

It's easy with find and ==:

>> A = [
    1  1
    1  1
    1  2
    1  2
    2  2
    2  2
    3  2
    3  2
    3  3
    4  3
    4  4];

>> R = randsample(4,1)
>> find(A(:,1) == R)

R =
     4
ans =
    10
    11

Or, as indicated by igor milla,

>> I = randi(11)
>> A(I, :)

I =
     9
ans =
     3     3

Upvotes: 3

Related Questions