MATLAB: Indexing nearest number problem

indexingnearest

Hi all, I'm hoping for some help on this problem.
I have a matrix A 384×320. every point represents a depth. I also have a vector b 1×50, which is depths from 0-500.
I want to find the index of b, that corresponds to the nearest depth within matrix A.
For example: A[1,1] = 256 b [1:10:500]
So the corresponding nearest index on b that is closest to 256 of A, would be index 26 (or b 251).
I've tried a few loops, but nothing working…this is the closest I can come, but not correct.
for i=1:384 for j=1:320 x=nearest(b<=A(i,j)); end end
Thank you in advance for your time! Corinne

Best Answer

Get the index for a single element of A:
A = rand(384, 320);
b = rand(1, 50);
[absDiff, Index] = min(abs(A(1, 1) - b));
Get the index for all elements at once: EDITED: Get MIN over 2nd dimension - thanks Matt Fig!
[absDiff, Index] = min(abs(bsxfun(@minus, A(:), b)), [], 2);
Index = reshape(Index, size(A));
If b is equidistant the calculation can be made much more efficient by scaling the values of A and a simple ROUND.