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
采纳的回答
更多回答(1 个)
Teja Muppirala
2011-6-12
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 个评论
Jan
2011-6-12
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!