Find the closest value in a matrix matlab -


how can find closest element in matrix in matlab?

suppose have matrix of size 300x200 , want find value , index of element in matrix closest element given.

does know how can done in matlab? know how given array can not figure out how done matrix.

a smaller case might understand -

code

%%// given big matrix, taken matrix of random numbers demo a1 = rand(10,5); %%// replace 300x200 matrix  %// demo, let assume, looking element happens closest element in 4th row , 5th column, verified @ end  element = a1(4,5)+0.00001; %%// element in search  %%// find linear index of location [~,ind] = min(reshape(abs(bsxfun(@minus,a1,element)),numel(a1),[]));  %%// convert linear index row , column numbers [x,y] = ind2sub(size(a1),ind)  

output

x =      4  y =        5 

as can seen, output matches expected answer.

extended part: if have set of search numbers, can process them closeness efficiently using bsxfun. shown below -

code

%%// given big matrix, taken matrix of random numbers demo a1 = rand(10,5); %%// replace 300x200 matrix  %// array of search numbers search_array = [a1(4,5)+0.00001;a1(6,5)+0.00001;a1(4,4)+0.00001;a1(4,2)+0.00001];  %%// find linear index of location [~,ind] = min(abs(bsxfun(@minus,a1(:),search_array')));%//'  %%// convert linear index row , column numbers [x,y] = ind2sub(size(a1),ind)  

output

x =      4     6     4     4   y =      5     5     4     2 

Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -