How to speed up this code?

조회 수: 1 (최근 30일)
K E
K E 2014년 11월 13일
댓글: K E 2014년 11월 14일
I would like fast code to find the index of the closest element of a vector to a scalar. Here's what I am doing now,
someVector = [1 3.5 5 7 9];
someScalar = 4;
iClosest = find(abs(someVector - someScalar) == min(abs(someVector - someScalar)));
The returned index is 2 since the 2nd element is closest to 4. A parent program spends a lot of time on this line according to the profiler. I'd like to know if it can be done faster or if there's a built-in solution.

채택된 답변

Azzi Abdelmalek
Azzi Abdelmalek 2014년 11월 13일
[~,idx]=min(abs(someVector - someScalar))
  댓글 수: 1
K E
K E 2014년 11월 14일
Thanks, knew there was a more elegant way.

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

추가 답변 (0개)

카테고리

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