How to find the second closest number?

6 ビュー (過去 30 日間)
Yuli Hartini
Yuli Hartini 2017 年 1 月 5 日
回答済み: KSSV 2017 年 1 月 5 日
I have a matrix looks like this:
A = [1990;1993;1998;2001;2004 ]
And I would like to find the closest value to f=1999 (in this case the first closest value is certainly 1998), but how can I find the second closest value (2001) after I found the first value.
Thanks before
  1 件のコメント
David Goodmanson
David Goodmanson 2017 年 1 月 5 日
Hi Yuli, if you take abs(A-your_number) and sort it, you will get the entire list of distances. The sort command also has a second output that will show you the location of each one in the unsorted array.

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

採用された回答

KSSV
KSSV 2017 年 1 月 5 日
clc; clear all ;
A = [1990;1993;1998;2001;2004 ] ;
f = 1999 ;
[val,idx] = sort(abs(f-A)) ;
A(idx)

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeShifting and Sorting Matrices についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by