Find closest value in large array
258 次查看(过去 30 天)
显示 更早的评论
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!
0 个评论
回答(2 个)
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
0 个评论
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.
0 个评论
另请参阅
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!