0

I have a 3D array that looks like this:

edges = round(rand(20,20,20)));

I then create a random list of indices as follows:

indices = floor(rand(10000,3)*(19))+1;

So if I try to use the first row of the indices 2D array to access an element in the edges array, I do:

>>> edges(indices(1,1),indices(1,2),indices(1,3))
>>> ans = 1

I figured, if I wanted to get the value of edges at all of the index positions, I could do

>>> edges(indices)

but that returns an 10000 by 3 matrix. I would expect a 10000 by 1 matrix with values of edges at positions specified by each row of indices. What is going on here, and is there a way to get the values I want without using any for loops?

1
  • 1
    read about sub2ind and ind2sub Commented May 5, 2020 at 0:27

1 Answer 1

1

Yes. Use a single index into edges instead of 3:

edges = round(rand(20,20,20));
indices = floor(rand(10000,1)*(20^3-1))+1;
edges(indices)

You should use randi() instead of round(rand()) as well, because round(5*rand())+1 will give you fewer 1s and 6s than 2s, 3s, 4s, 5s.

edges = randi(2,20,20,20)-1;
indices = randi(20^3,10000,1);
edges(indices)
Sign up to request clarification or add additional context in comments.

Comments

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.