How to choose value from array based on closest value
4 ビュー (過去 30 日間)
古いコメントを表示
I have a 41x2 array. I want to take an input variable, find the closest value in the first column, and assign the corresponding value in the second column to a new variable.
Any pointers on how I would go about doing this?
For example:
- Input value is x = 3.2
- Search first column in array for 3.2
- Closest value is 3
- Value in 2nd column corresponding to 3 is 500
- Store 500 to new variable y
Thanks!
0 件のコメント
採用された回答
Walter Roberson
2022 年 7 月 13 日
If the values in the first column are sorted, use interp1() with 'nearest'
その他の回答 (1 件)
Ruchika P Barman
2022 年 7 月 13 日
It is my understanding that you are trying to get the element closest to the input number by comparing with all the elements in the matrix column-wise. The following code should be able to achieve the same.
V=[0.87]
arr = rand(41,2)
for c=1:2
N=arr(:,c);
A = repmat(N,[1 length(V)]);
[minValue,closestIndex] = min(abs(A-V'));
closestValue = N(closestIndex);
V=closestValue;
end
V
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Logical についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!