How to find the nth is the higher than and closest to 0.3

1 回表示 (過去 30 日間)
yang-En Hsiao
yang-En Hsiao 2019 年 10 月 2 日
回答済み: Shubham Gupta 2019 年 10 月 2 日
A=[5 56 6.1 0.29 0.32 15 ]
I want to find a value which not only be the closest to 0.3,but also higher than 0.3
As we know ,0.32 should be the answer,and 0.32 is the 5th number in A vector,how do i write a code to let Matlab tell the 5th is higher and closest number to 0.3 ?

採用された回答

Star Strider
Star Strider 2019 年 10 月 2 日
One approach:
A=[5 56 6.1 0.29 0.32 15 ];
Av = A(A > 0.3);
[~,idx] = min(abs(Av-0.3));
Out = Av(idx)
Idx = find(A == Out)
producing:
Out =
0.32
Idx =
5
This first selects the elements of ‘A’ that are larger than 0.3, then finds the closest value to 0.3. It then uses that value to find the position in ‘A’. (I also tested this on some random ‘A’ vectors.)

その他の回答 (1 件)

Shubham Gupta
Shubham Gupta 2019 年 10 月 2 日
One of the several ways:
A=[5 56 6.1 0.29 0.32 15 ];
[vec,ind] = sort(A);
id = find(vec>0.3,1);
rqd_value = vec(id) % Required Value
rqd_index = ind(id) % Required Index

カテゴリ

Help Center および File ExchangeStartup and Shutdown についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by