indexing nearest number problem
Mostra commenti meno recenti
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
Risposta accettata
Più risposte (1)
Teja Muppirala
il 12 Giu 2011
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 Commento
Jan
il 12 Giu 2011
What about: interp1(b, 1:numel(b), A, 'nearest');
But unfortunately Matlab's INTERP1 is not implemented efficiently, in opposite to HISTC.
Categorie
Scopri di più su Matrix Indexing in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!