As a part of teaching a course in economics, I had to supply Matlab code 
for solving a particular kind of problem. Many times, we have to evaluate a 
function outside of the grid where we know the value, and we use linear 
interpolation to approximate these values. 

I wanted to use Interpolations.jl, but it seems that everything has to be 
done based on x (grid where we know the function values) being a range. It 
may seem weird, but I do not know from the beginning what the x's are going 
to be, as the are calculated and changed throughout the algorithm. 

At some point in the algorithm, I have a matrix filled with x_i's (points 
where I want to interpolate), and (x,y) which is the tuple of grids where I 
know the function values and the function values themselves. My question 
is, is there any way of simplifying the handling of the differences between 
scalars, vector, and matrices? *(<- this is where my question is hidden in 
the wall of text)* Maybe it would be easier if there was a function such as 
histc to calculate loc (location aka what bin are we in).

I probably also have to add, that it is on purpose that I treat < first 
grid point and between the first and second grid point (and likewise in the 
upper end) the same. If we are outside of the grid, I want to use the 
nearest gradient to extrapolate. 


function interp1 (x::Vector, y::Vector, xi::Float64)
    N = length(x)
    loc = zeros(m,n)
    place = 1
    for i = 2:(N-1)
        place+= xi[j,k] >= x[i]
    end
    loc=place
    return y[loc]+(xi-x[loc]).*(y[loc+1]-y[loc])./(x[loc+1]-x[loc])
end

function interp1 (x::Vector, y::Vector, xi::Matrix)
    m,n = size(xi)
    N = length(x)
    loc = zeros(m,n)
    for k = 1:n
        for j = 1:m
            place = 1
            for i = 2:(N-1)
                place+= xi[j,k] >= x[i]
            end
            loc[j,k]=place
        end
    end
    return y[loc]+(xi-x[loc]).*(y[loc+1]-y[loc])./(x[loc+1]-x[loc])
end

function interp1 (x::Vector, y::Vector, xi::Vector)
    n = length(xi)
    N = length(x)
    loc = zeros(n)
    for k = 1:n
        place = 1
        for i = 2:(N-1)
            place+= xi[k] >= x[i]
        end
        loc[k]=place
    end
    return y[loc]+(xi-x[loc]).*(y[loc+1]-y[loc])./(x[loc+1]-x[loc])
end

Reply via email to