考虑以下矩阵:
0 3 0 1 1 4
1 3 5 6 7 0
2 5 6 2 6 1
4 4 2 1 5 1
当我指定一个元素的位置时,我想获取具有相同值的最近元素的位置。例如,如果我选择第3行第3列中的元素,即“6”,我会比如获取最接近的‘6’的行列值,在本例中,它在第2行第4列。同样,对于第4行第4列的‘1’,最接近的在第4行,第 5 列和第 4 行,第 6 列,其中任何一个都可以。我已经查找了“bwdist”和“find”函数,但它们没有给出正确的结果。任何人都可以帮助我吗?
编辑:
a1 = randi(10,10,5);
disp(a1);
%// For an array of search numbers
search_array = a1(4,5);
disp(search_array);
%%// 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)
“min”函数在这里不起作用,因为所需元素所在的每个位置都将转换为零,并且“min”按行扫描矩阵并给出第一个零的位置。以下是这样的案例:
2 6 10 9 2
6 6 7 5 3
1 8 5 2 1
8 1 9 5 5
9 7 6 4 3
10 6 6 5 3
10 2 7 9 5
6 10 4 5 2
3 6 3 4 5
2 5 6 4 8
即使第 4 行第 5 列中的“5”旁边有一个“5”,第 10 行第 2 列中的“5”也被选中。
最佳答案
假设 A
是输入二维矩阵,这可能是一种方法 -
%// Row and column indices of the "pivot"
row_id = 4;
col_id = 5;
%// Get the linear index from row and column indices
lin_idx = sub2ind(size(A),row_id,col_id)
%// Logical array with ones at places with same values
search_matches = false(size(A));
search_matches(A==A(lin_idx)) = 1;
%// Create a logical array with just a single 1 at the "pivot"
A_pivot = false(size(A));
A_pivot(lin_idx) = 1;
%// Use BWDIST to find out the distances from the pivot to all the places
%// in the 2D matrix. Set the pivot place and places with non-similar
%// values as Inf, so that later on MIN could be used to find the nearest
%// same values location
distmat = bwdist(A_pivot)
distmat(lin_idx) = Inf
distmat(~search_matches)=Inf
[~,min_lin_idx] = min(distmat(:))
[closest_row_idx,closest_col_idx] = ind2sub(size(A),min_lin_idx)
关于matlab - 在matlab中查找矩阵中具有相同值的最接近元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28378680/