简体   繁体   中英

Matlab matrix indexing from 2 Arrays (X,Y)

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM