indexing nearest number problem

Hi all, I'm hoping for some help on this problem.
I have a matrix A 384x320. every point represents a depth. I also have a vector b 1x50, 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

 采纳的回答

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.

3 个评论

Thanks Jan! works great!
I took the first part and ran it in a loop to go through all the elements. I know not the fastest way, but a little easier to understand at first.
When I run through all the elements above, Index only ends up being 1x50...
If I am not mistaken, Jan simply made a dimensional error.
[absDiff, Index] = min(abs(bsxfun(@minus, A(:), b)),[],2);
Index = reshape(Index, size(A));
Thanks Matt. That fixed the problem.

请先登录,再进行评论。

更多回答(1 个)

For this problem, I suspect HISTC may be a better (faster and more memory efficient) alternative to BSXFUN.
A = rand(384,320);
b = sort(rand(1,50));
tic
[~,Index1] = histc(A,[-Inf interp1(1:numel(b),b,0.5 + (1:numel(b)-1)) Inf]);
toc
tic
[absDiff, Index2] = min(abs(bsxfun(@minus,A(:),b)),[],2);
Index2 = reshape(Index2,size(A));
toc
isequal(Index1,Index2)
For larger data, BSXFUN will give poor performance or run out of memory, like this:
A = rand(1000,1000);
b = sort(rand(1,10000));
tic
[~,Index1] = histc(A,[-Inf interp1(1:numel(b),b,0.5 + (1:numel(b)-1)) Inf]);
toc
tic
[absDiff, Index2] = min(abs(bsxfun(@minus,A(:),b)),[],2);
Index2 = reshape(Index2,size(A));
toc

1 个评论

What about: interp1(b, 1:numel(b), A, 'nearest');
But unfortunately Matlab's INTERP1 is not implemented efficiently, in opposite to HISTC.

请先登录,再进行评论。

类别

帮助中心File Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by