2

I have X and Y positions for a large array and I would like to use them to define what the contents of that position. I could run a for loop to define the positions but I think there would be a faster method. I tried to use the array position define function.

x = [6,2,3]
y = [1,2,3]

c = [1,1,1,2,2,3;...
     1,1,1,2,2,5;...
     2,2,1,4,2,3;...
     1,1,4,3,2,3;...
     1,2,3,4,5,3;...
     1,2,3,5,4,2];

When I type the equation above it results in the answer below

c(y,x)
ans =
 1     2     3
 1     1     1
 2     2     1

What I'm looking for are the 1:1 positions from the arrays.

c(y(1),x(1))
c(y(2),x(2))
c(y(3),x(3))

Is there any way to limit the arrays to a linear sequence? my only guess right now is to reshape the arrays into a cell matrix containing the individual a and b and then perform a cellfun. but I think I'm making it to complicated.

Hojo.Timberwolf
  • 985
  • 1
  • 11
  • 32

1 Answers1

3

You have to convert the locations into linear indices first, then you can grab the correct elements in the desired linear sequence. You can use sub2ind to help you do that:

ind = sub2ind(size(c), y, x); % Get linear indices
v = c(ind); % Get the elements

Doing this thus gives:

>> v = c(ind)

v =

     3     1     1

You can verify for yourself that each pair of (y,x) gives you the right element you're looking for. For example, when y = 1 and x = 6, the element retrieved is 3 and so on.

rayryeng
  • 102,964
  • 22
  • 184
  • 193
  • 1
    @Hojo.Timberwolf As further reading, this is the reason why your result is a matrix rather than a linear sequence: https://stackoverflow.com/a/19731104/3250829. When you specify arrays for both the rows and columns of a matrix, it finds the rows and columns that intersect and returns a subset of that matrix. Check out the post for further details. With the post, this is why you need to convert each pair of row and column coordinates into a single linear index. That way, you'll be able to extract individual elements rather than a subset of the matrix. – rayryeng Sep 06 '17 at 05:47