Search code examples
arraysmatlabfunctioncell-array

Returning specific items from an array given an array of coordinates in MATLAB


Let's suppose I have some (numerical) array called A_array that is N1xN2xN3 in size, and two more vector arrays x = [x1,x2, ... ,xn], y = [y1,y2, ... ,yn] where size(x) = size(y). (where n < N1,N2,N3)

Right now I'm trying to get the values in A_array at (t,x1,y1), (t,x2,y2), etc. so that the result is an array that looks like this: [A_array(t,x1,y1), A_array(t,x2,y2), ... , A_array(t,xn,yn)]

I tried writing A_array(t,x,y), but this returns an nxn array, which is not what I would like. I've tried to write out the problem into words to the best of my ability... Could this also be generalized to multiple lists i.e. x,y,z,etc.?


Solution

  • Use sub2ind as shown here -

    A_array = A(sub2ind(size(A),repmat(t,1,numel(x)),x,y))
    

    For higher dimensional array cases with x, y, z, z2 etc. as the indexing arrays, just append them like this -

    A_array = A(sub2ind(size(A),repmat(t,1,numel(x)),x,y,z,z2))
    

    If t is used for indexing into some other dimension, like maybe the 3rd dimension -[A_array(x1,y1,t), A_array(x2,y2,t), ... , A_array(xn,yn,t)], then change the position of t inside sub2ind accordingly. So, for this modified case you would have -

    A_array = A(sub2ind(size(A),x,y,repmat(t,1,numel(x))))