two arrays defining 2d coordinates, as array indices, in matlab/octave
Question
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
Solution
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)
OTHER TIPS
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.