4.0

4.0 | 2 ratings Rate this file 57 Downloads (last 30 days) File Size: 1.77 KB File ID: #2838

findnearest.m

by Thomas Benson

 

09 Dec 2002 (Updated 23 Dec 2002)

Find the nearest value in an array to a test value.

| Watch this File

File Information
Description

Find the index or subscripts of the nearest value in an array to a test value. A bias argument can be included to only return values greater or less than the search value.

MATLAB release MATLAB 6.0 (R12)
Tags for This File  
Everyone's Tags
Tags I've Applied
Add New Tags Please login to tag files.
Comments and Ratings (3)
18 Dec 2004 Glenn Hartwell

Good function! It does just what I need.

24 Mar 2005 Felipe Leon

A bit slow, but works great for my needs. If there is a optimal (faster) way of doing this, will someone please share.

Ran into a small issue with repeated values, where it returned more than one value, causing an error in my routine. This can be corrected on my end, but to do so in here, I just changed the code a little bit (as below):

if nargout==1 | nargout==0
    
    if all(isinf(srcharray(:)))
        r = [];
    else
        clear r_temp;
        r_temp = find(abs(srcharray)==min(abs srcharray(:))));
        if length(r_temp)>1
             r = r_temp(1);
        else
             r = r_temp;
        end
    end
end

28 Aug 2009 PraveenKumar Jayaram

Great component!
This solved my problem...

Please login to add a comment or rating.
Updates
23 Dec 2002

Improved to optionally include the found nearest value as a third output argument (V).

Tag Activity for this File
Tag Applied By Date/Time
approximation Thomas Benson 22 Oct 2008 06:54:53
interpolation Thomas Benson 22 Oct 2008 06:54:53
find nearest Thomas Benson 22 Oct 2008 06:54:53
array Thomas Benson 22 Oct 2008 06:54:53
bias argument Thomas Benson 22 Oct 2008 06:54:53
test value Thomas Benson 22 Oct 2008 06:54:53
find Thomas Benson 22 Oct 2008 06:54:53
nearest Thomas Benson 22 Oct 2008 06:54:53

Contact us at files@mathworks.com