# Select nearest value on a vector for a given value

2 ビュー (過去 30 日間)
Luis Marcos 2018 年 3 月 8 日
コメント済み: Fangjun Jiang 2018 年 3 月 11 日
Hi.
I would like to know if you can help me.
I have to get the vector index where its value is closer o nearest to a given value, for example.
i have this vector.
0 1 2 3 4 5 6 7 index
Value -172.0000 | -130.8750 | -89.7500 | -48.6250 | -7.5000 | 33.6250 | 74.7500 | 115.8750 | 157.0000
and if i want to look for the -8, it want to get the index 3 because -8 is between .-48.625 and -7.5, and so on, if i looking for 157, i should get the index 7
i have this code by far, but it isnt working the way i want.
MEQ=[fil,col];
for i=1 :fil%i will store the index in a matrix, so i have to loop over rows
for j=1 :col%loop over matrix columns
for w=1 :numel(recta)%this is the vector
[c,indice]=min(abs(recta-E(i,j)));%here i get the index
MEQ(i,j)=indice;%change the current vector value for the index
end
end
end
can some one give me an idea please
Thank you

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

### 採用された回答

Roger Stafford 2018 年 3 月 8 日

I notice that your vector 'Value' has ascending elements. If we can assume that, the following can be used:
s = -8; % Or whatever value is being sought
index = sum(Value<s)-1;
Note that this will give a -1 result if s is smaller than all the elements of 'Value' or an 8 index if it is greater than all of 'Value'. If you want to prevent these two possibilities, do this afterwards:
index = min(max(index,0),length(Value)-2);
##### 1 件のコメント-1 件の古いコメントを表示-1 件の古いコメントを非表示
Luis Marcos 2018 年 3 月 10 日
Thank you, it works perfectly

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

### その他の回答 (1 件)

Fangjun Jiang 2018 年 3 月 8 日
Can you use built-in function?
X=10:10:100;
Y=1:10;
out=interp1(X,Y,12,'nearest')
out=interp1(X,Y,18,'nearest')
##### 2 件のコメントなしを表示なしを非表示
Luis Marcos 2018 年 3 月 10 日
Thank you. But i cant understand what does that do.
Fangjun Jiang 2018 年 3 月 11 日
Your code above can be replaced with just one line.
MEQ=interp1(recta,(1:length(recta))-2,E,'nearest')

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

### カテゴリ

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