Find closest value in large array

277 Ansichten (letzte 30 Tage)
Andrew
Andrew am 17 Mär. 2015
Beantwortet: Anusha B am 17 Mär. 2015
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!

Antworten (2)

James
James am 17 Mär. 2015
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 am 17 Mär. 2015
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.

Kategorien

Mehr zu Programming finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by