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 日

0 投票

[~,idx]=min(abs(someVector - someScalar))

1 件のコメント

K E
K E 2014 年 11 月 14 日
Thanks, knew there was a more elegant way.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeMatrix Indexing についてさらに検索

タグ

質問済み:

K E
2014 年 11 月 13 日

コメント済み:

K E
2014 年 11 月 14 日

Community Treasure Hunt

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

Start Hunting!

Translated by