How to find the closest data row index

조회 수: 6 (최근 30일)
Kanakaiah Jakkula
Kanakaiah Jakkula 2017년 9월 18일
편집: KL 2017년 9월 18일
Input data (sort by time): M:
1.0
1.2
3.1
4.0
1.2
1.0
4.8
given data:
V:1.2
I want to find the most closer one in the input data
I use the below function:
[~,idx] = min(sum(bsxfun(@minus,M,V).^2,2));
M(idx,:)
But here, there two rows (duplicate data) row2 &row5, if this is the case, I want to pick the more recent row index i.e., row5 (but the present code giving row 2).

채택된 답변

Cam Salzberger
Cam Salzberger 2017년 9월 18일
Hello Kanakaiah,
I think you're pretty much on the right track, though there's no need for bsxfun if you just want one index out. Since min will always return the index of the first element found, just flip it around before calling min:
dist = abs(A-V);
[~, revIdx] = min(dist(end:-1:1)); % Could also use flipud
idx = numel(A)-revIdx+1;
-Cam
  댓글 수: 2
Kanakaiah Jakkula
Kanakaiah Jakkula 2017년 9월 18일
Sir,
my input data is 3x10 matrix(i just cut down the data), original data is:
Hi, I have below matrix:
M:
1.5 2.1 5.1 4.0
1.0 2.9 3.6 6.9
1.0 2.9 3.6 6.9
1.1 2.3 2.8 3.9
V: 1.0 2.9 3.6 6.9
Cam Salzberger
Cam Salzberger 2017년 9월 18일
편집: Cam Salzberger 2017년 9월 18일
Alright, so your "distance" in this case is the 2-norm of the vector with each row of M? In that case, you can just change how distance is calculated, but the rest of my code should still work. In R2016b and later, you can use implicit expansion to allow a little shortcut:
dist = sum((M-V).^2, 2);
Otherwise you have to get fancy with repmat:
Vexp = repmat(V, size(M, 1), 1);
dist = sum((M-Vexp).^2, 2);

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

KL
KL 2017년 9월 18일
편집: KL 2017년 9월 18일
EDITED for 2D matrix,
A = abs(M-V);
ind = arrayfun(@(k) find(A(:,k)==min(A(:,k)),1,'last'),1:length(V))

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by