how to find the index of the row

2 ビュー (過去 30 日間)
Imner Renmi
Imner Renmi 2016 年 7 月 7 日
編集済み: Imner Renmi 2016 年 7 月 7 日
Hi,
I want to get the row number in the following case. Say one has a 5 by 1 vector [1;2;3;4;5].
If I have the scalar '4.5' (which is not in that vector) then I know that 4.5 is between 4 and 5. What I want is to compare 4.5 with all the numbers in the vector. Then Matlab should be able to tell that 4.5 is between 4 and 5. My goal is to get the row number of the scalar '4'.
Consequently, if I have a scalar '3.5' then Matlab should be able to tell that 3.5 is between 3 and 4, and in this case I would like to obtain the row number of the scalar '3'
I just do not know how I could code this in Matlab.
Many thanks

採用された回答

James Tursa
James Tursa 2016 年 7 月 7 日
編集済み: James Tursa 2016 年 7 月 7 日
If you are looking for the closest value:
x = your vector
s = your scalar
[~,row] = min(abs(x-s));
If you are looking for the first number <= your scalar and x is sorted increasing:
row = find((x-s) >= 0,1);
If something else, please specify.
  3 件のコメント
James Tursa
James Tursa 2016 年 7 月 7 日
編集済み: James Tursa 2016 年 7 月 7 日
Does the posted code ( row and row+1 ) do what you want? Or Azzi's or Andrei's Answers?
Imner Renmi
Imner Renmi 2016 年 7 月 7 日
編集済み: Imner Renmi 2016 年 7 月 7 日
Yes, The first code does seem to do what I want. If something strange occurs I'll just post a new question. Thanks a lot for your help.

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

その他の回答 (2 件)

Azzi Abdelmalek
Azzi Abdelmalek 2016 年 7 月 7 日
編集済み: Azzi Abdelmalek 2016 年 7 月 7 日
v=[8;6;1;2;3;7;5;4]
m=3.5
mv=[m ;v]
[ii,jj]=sort(mv)
idx=find(jj==1)
% m is between a1 and a2,
idx1=jj(idx-1)
idx2=jj(idx+1)
a1=mv(idx1)
a2=mv(idx2)

Andrei Bobrov
Andrei Bobrov 2016 年 7 月 7 日
p = [1;2;3;4;5]
z = [3.5,4.5]
[~,out] = histc(z,p)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by