较小的情况下,可能会帮助你理解 -
代码
%%// Given big matrix, taken as a matrix of random numbers for demo
a1 = rand(10,5); %%// Replace this with your 300X200 matrix
%// For demo, let us assume, you are looking for the element that happens to be closest to the element in the 4th row and 5th column, which will be verified at the end
element = a1(4,5)+0.00001; %%// The element in search
%%// Find the linear index of the location
[~,ind] = min(reshape(abs(bsxfun(@minus,a1,element)),numel(a1),[]));
%%// Convert the linear index into row and column numbers
[x,y] = ind2sub(size(a1),ind)
输出
x =
4
y =
5
可以看出,产量预期的应答相匹配。
扩展部分:如果您有一组搜索数字,您可以使用bsxfun非常有效地处理它们的密切程度。这是如下图所示 -
代码
%%// Given big matrix, taken as a matrix of random numbers for demo
a1 = rand(10,5); %%// Replace this with your 300X200 matrix
%// For an 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 the linear index of the location
[~,ind] = min(abs(bsxfun(@minus,a1(:),search_array')));%//'
%%// Convert the linear index into row and column numbers
[x,y] = ind2sub(size(a1),ind)
输出
x =
4 6 4 4
y =
5 5 4 2