Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interpn - changing output

I have 4 grids:

  1. kgrid which is [77x1]
  2. x which is [15x1]
  3. z which is [9x1]
  4. s which is [2x1]

Then I have a function:

  1. kprime which is [77x15x9x2]

I want to interpolate kprime at some points ksim (750 x 1) and zsim (750 x 1) (xsim is a scalar). I am doing:

[ks, xs, zs, ss] = ndgrid(kgrid, x, z, [1;2]);
Output = interpn(ks, xs, zs, ss, kprime, ksim, xsim, zsim, 1,'linear');

The problem with this interpolation is that the output given is for all combinations of ksim and zsim, meaning that the output is 750x750. I actually need an output of 750x1, meaning that instead of interpolation at all combinations of ksim and zsim I only need to interpolate at ksim(1,1) and zsim(1,1), then ksim(2,1) and zsim(2,1), then ksim(3,1) and zsim(3,1), etc.

In other words, after getting Output I am doing:

Output = diag(squeeze(Output));

I know I can use this output and then just pick the numbers I want, but this is extremely inefficient as it actually interpolates on all other points which I actually do not need. Any help appreciated.

like image 951
phdstudent Avatar asked Aug 28 '16 16:08

phdstudent


1 Answers

tl;dr: Change xsim and (ssim) from scalars to vectors of the same size as ksim and zsim

Output = interpn (ks, xs, zs, ss,           ...
                  kprime,                   ...
                  ksim,                     ...
                  repmat(xsim, size(ksim)), ... % <-- here
                  zsim,                     ...
                  repmat(1, size(ksim)),    ... % <-- and here
                  'linear');


Explanation:

The ksim, xsim, zsim, and ssim inputs all need to have the same shape, so that at each common position in that shape, each input acts as an "interpolated subscript" component to the interpolated object. Note that while they all need to have the same shape, this shape can be arbitrary in terms of size and dimensions.

Conversely, if you pass vectors of different sizes (after all, a scalar is a vector of length 1), these get interpreted as the components of an ndgrid construction instead. So you were actually telling interpn to evaluate all interpolations on a grid defined by the vectors ksim, and zsim (and your singletons xsim and ssim). Which is why you got a 2D-grid-looking output.


Note that the same scheme applies with the constructing vectors as well (i.e. ks, xs, zs and ss) i.e. you could have used "vector syntax" instead of "common shape" syntax to define the grid instead, i.e.
Output = interpn(kgrid, x, z, s, kprime, % ...etc etc

and you would have gotten the same result.

like image 143
Tasos Papastylianou Avatar answered Nov 11 '22 09:11

Tasos Papastylianou