Determining the appropriate range for the given number.

I want to know, if I have a number such as 1.5 and I have 120 equal segments of number-line from 0.00 to 6.00 how can I determine in which segment this number (in this case 1.5) can be placed. I know I can use 'if-elseif' but for checking 120 case with 'if-elseif' seems very difficult. Is there any other way to do it?

 採用された回答

KSSV
KSSV 2019 年 3 月 22 日
編集済み: KSSV 2019 年 3 月 22 日

0 投票

x = 1:120 ;
y = linspace(0.,6,120) ;
xi = 1.5 ;
yi = floor(interp1(y,x,xi)) ;
fprintf('%f should be placed between %f and %f\n',xi,y(yi),y(yi+1))
OR:
x = linspace(0.,6,120) ;
xi = 1.5 ;
[val,idx] = min(abs(x-xi)) ;
fprintf('%f should be placed between %f and %f\n',xi,x(idx-1),x(idx))
OR:
x = linspace(0.,6,120) ;
xi = 1.5 ;
idx = knnsearch(x',xi) ;
fprintf('%f should be placed between %f and %f\n',xi,x(idx-1),x(idx))

1 件のコメント

Alok Kumar Dubey
Alok Kumar Dubey 2019 年 3 月 22 日
Hi KSSV,
Thank you so much for your effort to help me. Your suggestions worked perfectly for me.
thanks
Alok

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

その他の回答 (0 件)

カテゴリ

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

製品

リリース

R2016b

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by