2

I have read through the examples here, but it does not seem to include the following case.

Let A be a three dimensional array with dimensions 128 x 128 x 3.

I want to pick sets of 3 integers at random from this array, by picking random pairs for the first two dimensions. This is my current attempt:

rng(1);                                         
choicex = randi(128, 1, 16)                
choicey = randi(128, 1, 16)                 
random_values = A(choicex, choicey,:)  

Unfortunately, this the matrix random_values is now 16 x 16 x 3, when I want it to be 16 x 3. Taking one slice of this does not work because then either all the first indices would be the same or all the second indices would be the same. I do not require that random_values carries the original indices.

Is there any way to achieve this in matlab directly with index notation, without writing a for loop?

Per the given answer, I have updated the question.

1 Answer 1

3

There are two problems with your code:

  1. randi(nmax, i, j) returns a size (i,j) matrix of random integers from 1..nmax. In your case, nmax obviously has to be 128, not 256.

  2. matlab has 1-based indexing, not 0-based, so do not subtract 1.

This works for me:

>> A = randn(128,128,3);
>> choicex = randi(128, 1, 16);
>> choicey = randi(128, 1, 16);
>> B = A(choicex, choicey,:);
>> size(B)

ans =

    16    16     3

But this will give all triples that are on all combinations of the given rows and columns, so 256 triples in total. What you really want can be achieved with sub2ind, but it is not an easy expression:

A(sub2ind(size(A), repmat(choicex,3,1), repmat(choicey,3,1), ...
    repmat([1;2;3],1,16)))

or with a few characters less:

A(sub2ind(size(A), [1;1;1]*choicex, [1;1;1]*choicey, [1;2;3]*ones(1,16)))
Sign up to request clarification or add additional context in comments.

2 Comments

+1, Your answer does solve the error, but I'm trying to get 16 sets of 3 values, not 256 sets of 3 values.
If I replaced 16 with 4 above, it would get me 16 values, but there would be shared indices among the points selected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.