views:

246

answers:

2

Hi,

I have a 2D array, call it 'A'. I have two other 2D arrays, call them 'ix' and 'iy'. I would like to create an output array whose elements are the elements of A at the index pairs provided by x_idx and y_idx. I can do this with a loop as follows:


for i=1:nx
    for j=1:ny
        output(i,j) = A(ix(i,j),iy(i,j));
    end
end

How can I do this without the loop? If I do output = A(ix,iy), I get the value of A over the whole range of (ix)X(iy).

Thank you, Jason

+1  A: 

This is the one-line method which is not very efficient for large matrices

reshape(diag(A(ix(:),iy(:))),[ny nx])

A clearer and more efficient method would be to use sub2ind. I've incorporated yuk's comment for situations (like yours) when ix and iy have the same number of elements:

newA = A(sub2ind(size(A),ix,iy));

Also, don't confuse x and y for i and j in notation - j and x generally represent columns and i and y represent rows.

Jacob
Man, sorry for all the edits! I'm not thinking clearly today.
Jacob
The sub2ind code can be just: newA = A(sub2ind(size(A),ix,iy));
yuk
Perfect! Thank you very much!
Jason
+5  A: 

A faster way is to use linear indexing directly without calling SUB2IND:

output = A( size(A,1)*(iy-1) + ix )

... think of the matrix A as a 1D array (column-wise order)

merv
Wow, that is much faster! Thank you.
Jason
@Jacob: Actually, I think `output` will end up the same size as `ix`.
gnovice