changeset 10427:62bb59f927b1

scripts/general/interp2.m, scripts/general/interpn.m: For nearest neighbour interpolation ceil (instead of floor) at the center of the data intervals to be compatible with Matlab. Add test.
author Soren Hauberg <hauberg@gmail.com>
date Sat, 20 Mar 2010 14:26:03 -0700
parents 4db7beace28e
children fb8c9db4a39c
files scripts/ChangeLog scripts/general/interp2.m scripts/general/interpn.m
diffstat 3 files changed, 19 insertions(+), 3 deletions(-) [+]
line wrap: on
line diff
--- a/scripts/ChangeLog	Sat Mar 20 11:01:04 2010 -0400
+++ b/scripts/ChangeLog	Sat Mar 20 14:26:03 2010 -0700
@@ -1,3 +1,10 @@
+2010-03-20  Soren Hauberg  <hauberg@gmail.com>
+
+	* general/interp2.m: For nearest neighbour interpolation ceil (instead of
+    floor) at the center of the data intervals to be compatible with Matlab.
+    Add test.
+	* general/interpn.m: Ditto.
+
 2010-03-19  Jaroslav Hajek  <highegg@gmail.com>
 
 	* strings/strmatch.m (strtrimr): Rewrite for correct behavior.
--- a/scripts/general/interp2.m	Sat Mar 20 11:01:04 2010 -0400
+++ b/scripts/general/interp2.m	Sat Mar 20 14:26:03 2010 -0700
@@ -231,8 +231,8 @@
       ZI = a(idx) + b(idx).*Xsc + c(idx).*Ysc + d(idx).*Xsc.*Ysc;
 
     elseif (strcmp (method, "nearest"))
-      ii = (XI - X(xidx) > X(xidx + 1) - XI);
-      jj = (YI - Y(yidx) > Y(yidx + 1) - YI);
+      ii = (XI - X(xidx) >= X(xidx + 1) - XI);
+      jj = (YI - Y(yidx) >= Y(yidx + 1) - YI);
       idx = sub2ind (size (Z), yidx+jj, xidx+ii);
       ZI = Z(idx);
 
@@ -581,3 +581,7 @@
 %!  assert(interp2(x,y,A,x,y,'linear'), A);
 %!  assert(interp2(x,y,A,x,y,'nearest'), A);
 
+%!test % for Matlab-compatible rounding for 'nearest'
+%! X = meshgrid (1:4);
+%! assert (interp2 (X, 2.5, 2.5, 'nearest'), 3);
+
--- a/scripts/general/interpn.m	Sat Mar 20 11:01:04 2010 -0400
+++ b/scripts/general/interpn.m	Sat Mar 20 14:26:03 2010 -0700
@@ -149,7 +149,7 @@
     endfor
     idx = cell (1,nd);
     for i = 1 : nd
-      idx{i} = yidx{i} + (y{i} - x{i}(yidx{i}) > x{i}(yidx{i} + 1) - y{i});
+      idx{i} = yidx{i} + (y{i} - x{i}(yidx{i}) >= x{i}(yidx{i} + 1) - y{i});
     endfor
     vi = v (sub2ind (sz, idx{:}));
     idx = zeros (prod(yshape),1);
@@ -256,3 +256,8 @@
 %! [x,y,z] = ndgrid(0:2);
 %! f = x.^2+y.^2+z.^2;
 %! assert (interpn(x,y,-z,f,1.5,1.5,-1.5), 7.5)
+
+%!test % for Matlab-compatible rounding for 'nearest'
+%! X = meshgrid (1:4);
+%! assert (interpn (X, 2.5, 2.5, 'nearest'), 3);
+