Find closest value in large array

조회 수: 66 (최근 30일)
Andrew
Andrew 2015년 3월 17일
답변: Anusha B 2015년 3월 17일
Hey guys,
I have a dataset that is around 4000 rows long and I want to write my script so the user can enter a pressure, and then the script will find the closest values in said data set. How do I go about this?
%------------------------------------------------------------------------%
% Request pressure limits %
%------------------------------------------------------------------------%
UL = input('Enter upper pressure limit (in hPa): ','s');
LL = input('Enter lower pressure limit (in hPa): ','s');
This is all I have so far, any help would be appreciated!

답변 (2개)

James
James 2015년 3월 17일
I have seen a solution to this before, I think the answer was to subtract the value you are looking for, then use the min function on the absolute value of the result. i.e.
a = [1 2 3 4 5]
i want to find the closet value to 3.2.
[m,i] = min(abs(a-3.2));
m is how close the value (3.2) was to the closest value in the array and i is the index at which it was found. in this example, m is 0.2 and i is 3.
hope that helps, james

Anusha B
Anusha B 2015년 3월 17일
One way to do this is as follows:
For example: Suppose there is a vector with 100 elements and you want to find an element closest to the value that you specify:
x=rand(100,1); %Generating a vector with 100 random elements.
x0=0.321; %Value specified
y=find((x-x0)<0.5); %Finding indices of all elements whose difference with the value specified is 0.5. (Here my error tolerance is 0.5)
z=x(y); %Creating a vector with the values that satisfy the above condition
closestval=min(z-x0); %Finding the value from this vector that is closest to the value specified.
Hope this helps.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by