-2

I am trying to get a few values from a 2D matrix

Consider the starting matrix:

>> test = randi(10,10)

test =

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

What I want to do is grab elements (1,4);(2,5);and(3,6) only

So I try

test([1,2,3],[4,5,6])

but that returns all combinations of the two indicies!

ans =

 6     3     1
 1     2     4
 8     4     8

Without this intermediate step, how do I do what I want in one line? There must be a way.

I cannot use the intermediate step because in actuality, my matrix is very large and so are my indices lengths so I will run out of memory.

1 Answers1

1

You can do this using sub2ind as was already pointed out at mathworks:

test(sub2ind(size(test),[1,2,3],[4,5,6]))

Applied to 3D

test = randi(10,10,10,10);
test(sub2ind(size(test),[1,2,3],[4,5,6], [3,3,3]))
m7913d
  • 10,244
  • 7
  • 28
  • 56
  • the problem is I'm trying to use this in a 3D array, so I cannot say test(index,3) where index represents the first 2 dimensions. Do you know a work around that? – Hubert S. Cumberdale Mar 15 '17 at 19:58
  • I provided an answer for 3D, please update your question to include the 3D case. – m7913d Mar 15 '17 at 20:05