Code covered by the BSD License  

Highlights from
Find values in a vector or function

image thumbnail

Find values in a vector or function

by

 

19 Apr 2011 (Updated )

For a function y=f(x), this script looks for all the "x" values for a desired value of "y" (y0).

varargout=findvalues(vector,yvalue)
function varargout=findvalues(vector,yvalue)

% FINDVALUES     function [valX,posX]=findvalues(vector,y0value)
%  
% Author: Adrian Lara-Quintanilla
% Date:   19/04/2011
% Date v1_r02:  16/03/2013
% 
% Description: This script finds the desired value (or the closest
% one) "y0value" and its position in "vector". The script returns two vectors,
% one with the found values "valX", and another one with the position of those
% values "posX". If y0value is not in the range of the vector, it yields
% NaN on vector of valX and posX

%% Start

% Initialize some variables
i=1;
i2=0;

maxvector=max(vector);
minvector=min(vector);
fprintf('Max is: %.2f and min is: %.2f\n',maxvector,minvector)
y0value=yvalue;
if y0value>maxvector
    varargout{1}=NaN;
    varargout{2}=NaN;
    fprintf('yvalue is not in the range of the function.\n The closest value is the maximum: %.2f\n',maxvector)
elseif y0value<minvector
    varargout{1}=NaN;
    varargout{2}=NaN;
    fprintf('yvalue is not in the range of the function.\n The closest value is the minimum: %.2f\n',minvector)
else
    
    % Program
    if vector(i)>=y0value
        flagi_1=1;
    else
        flagi_1=0;
    end
    
    for k=(i+1):length(vector)
        currentvalue=vector(k);
        previousvalue=vector(k-1);
        if vector(k)>=y0value
            flagi=1;
        else
            flagi=0;
        end
        
        if flagi_1~=flagi
            if abs(vector(k-1)-y0value)>=abs(vector(k)-y0value)
                foundvalue=vector(k);
                pos=k;
            else
                foundvalue=vector(k-1);
                pos=k-1;
            end
            i2=i2+1;
            valX(i2)=foundvalue;
            posX(i2)=pos;
        end
        flagi_1=flagi;
    end
    
    
    figure(999)
    plot(vector);hold on;
    plot(vector,'b+');hold on;
    plot(posX,valX,'go');hold on;
    plot([0 length(vector)],[y0value y0value],'k-');hold off;
    
    varargout{1}=valX;
    varargout{2}=posX;
end

Contact us