function varargout = c2(A,v)
%% I = c2(A,v)
% Finds the indices of A such that A(I) is the element closest
% to v.
%
% SYNTAX
%  index = c2(vector,value);
%  linear_index = c2(matrix,value);
%  [row,column] = c2(matrix,value);
%
% Written by Marcin Konowalczyk
% Timmel Group @ Oxford University

if isempty(v)
    if isvector(A)
        varargout = {[]};
    else
        varargout = {[],[]};
    end
    return
end

%% Check if outside of range
% Untested!
CHECK = false;
if CHECK
    if isvector(A)
        dA = mean(diff(A));
        if v > max(A)+(dA/2)
            warning('overflow');
        elseif v < min(A)-(dA/2)
            warning('underflow');
        end
    end
end

[~,I] = min(abs(A(:)-v));
if isvector(A)
    varargout = {I};
elseif ismatrix(A)
    if nargout == 1
        varargout = {I};
    else
        [I1,I2] = ind2sub(size(A),I);
        varargout = {I1,I2};
    end
else
    error('c2:invalidInput','A must be a vector or a matrix. Higher dim. not (yet) supported');
end
    