Input value and compare to values in an array

clc, clear, clf
M1=input('What is the Mach number? ');
Mach=[1.050,1.1,1.2,1.3,1.4,1.6,1.8,2,2.5,3,4,5,6,7,8,10];
Maxd=[0.558,1.515,3.944,6.662,9.427,14.652,19.183,22.974,29.797,34.073,38.774,41.118,42,440,43.791,44.429];
So I have this as my code. What I want to do is take an input mach number, find the closest value in the Mach array (rounding down) and then use the corresponding index of the Maxd array for calculations. I'm sure this is simpler than I think it is but I would very much appreciate the help.

 採用された回答

Star Strider
Star Strider 2018 年 11 月 3 日

1 投票

Using the interp1 (link) function:
M1=input('What is the Mach number? ');
Mach=[1.050,1.1,1.2,1.3,1.4,1.6,1.8,2,2.5,3,4,5,6,7,8,10];
Maxd=[0.558,1.515,3.944,6.662,9.427,14.652,19.183,22.974,29.797,34.073,38.774,41.118,42,440,43.791,44.429];
Result = interp1(Mach, Maxd, M1, 'previous')
M1 = 1.5
Result =
9.427
You can easily change the interpolation method if you want a different result.

3 件のコメント

Briana Staheli
Briana Staheli 2018 年 11 月 3 日
Thank you so much! this works like a charm!
madhan ravi
madhan ravi 2018 年 11 月 3 日
編集済み: madhan ravi 2018 年 11 月 3 日
+1 cool method @star strider
Star Strider
Star Strider 2018 年 11 月 3 日
As always, my pleasure!

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

その他の回答 (2 件)

madhan ravi
madhan ravi 2018 年 11 月 3 日
編集済み: madhan ravi 2018 年 11 月 3 日

0 投票

M1=input('What is the Mach number? ');
Mach=[1.050,1.1,1.2,1.3,1.4,1.6,1.8,2,2.5,3,4,5,6,7,8,10];
Maxd=[0.558,1.515,3.944,6.662,9.427,14.652,19.183,22.974,29.797,34.073,38.774,41.118,42,440,43.791,44.429];
[~,index]=min(abs(floor((Mach-(M1))))) %floor rounds down towards negative infinity
Maxd(index) %the value to be used in calculations
command window:
>> COMMUNITY
What is the Mach number? 3
index =
10
ans =
34.0730

4 件のコメント

Stephan
Stephan 2018 年 11 月 3 日
I think your code gives wrong result for input = 3
madhan ravi
madhan ravi 2018 年 11 月 3 日
check now @stephen
Stephan
Stephan 2018 年 11 月 3 日
編集済み: Stephan 2018 年 11 月 3 日
Wrong result for 1.15 i think - OP want to rounding down
Briana Staheli
Briana Staheli 2018 年 11 月 3 日
Thank you for the help!

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

Stephan
Stephan 2018 年 11 月 3 日

0 投票

M1=input('What is the Mach number? ');
Mach=[1.050,1.1,1.2,1.3,1.4,1.6,1.8,2,2.5,3,4,5,6,7,8,10];
Maxd=[0.558,1.515,3.944,6.662,9.427,14.652,19.183,22.974,29.797,34.073,38.774,41.118,42,440,43.791,44.429];
Value = Maxd(find((sort([Mach, M1]))==M1,1,'last')-1)

カテゴリ

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

質問済み:

2018 年 11 月 3 日

編集済み:

2018 年 11 月 3 日

Community Treasure Hunt

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

Start Hunting!

Translated by