Closest number problem in m-file

I need more help..
I have script looks like this
A = [2 5 9 15];
f = input('Enter input : ');
[val, idx]=sort(abs(f-A));
[val, idx]=min(abs(f-A));
A(idx)
If the input I enter is 3
Of course the output of A(idx) was 2
But I want the value output are 5 (the second closest of 3).
As well as for different inputs.
Please help me..
Thanks before

回答 (1 件)

KL
KL 2017 年 5 月 12 日

0 投票

[val, idx]=sort(abs(f-A));
A(idx(2))

3 件のコメント

Guillaume
Guillaume 2017 年 5 月 12 日
For the first line, even better if you're not using val:
[~, idx] = sort(abs(f-A));
which makes it clear that you only want the indices.
KL
KL 2017 年 5 月 12 日
編集済み: KL 2017 年 5 月 12 日
true, I just copy pasted her code
Yuli Hartini
Yuli Hartini 2017 年 5 月 12 日
Thank you guys..
This is very helpful.

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

カテゴリ

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

製品

質問済み:

2017 年 5 月 12 日

コメント済み:

2017 年 5 月 12 日

Community Treasure Hunt

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

Start Hunting!

Translated by