[英]Find closest element with same value in matrix in matlab
考慮以下矩陣:
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列的第1列的'1',最接近的是第4行,列5第4,col 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
是輸入2D矩陣,這可能是一種方法-
%// 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)
這種方法不需要任何工具箱。 如果不存在其他具有相同值的條目,則返回[]
。
A = [0 3 0 1 1 4
1 3 5 6 7 0
2 5 6 2 6 1
4 4 2 1 5 1]; %// data matrix
pos_row = 3; %// row of reference element
pos_col = 3; %// col of reference element
ref = A(pos_row,pos_col); %// take note of value
A(pos_row,pos_col) = NaN; %// remove it, to avoid finding it as closest
[ii, jj] = find(A==ref); %// find all entries with the same value
A(pos_row,pos_col) = ref; %// restore value
d = (ii-pos_row).^2+ (jj-pos_col).^2; %// compute distances
[~, ind] = min(d); %// find arg min of distances
result_row = ii(ind); %// index with that to obtain result
result_col = jj(ind);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.