MATLAB: Error in surfnorm function

MATLABsurfnorm

I'm using the surfnorm function in Matlab 2012b. Sometimes the normal vectors along one edge of the surface are reversed, but I can't figure out why it is reversing only the vectors at the edge.
Below is a sample code with a 3×3 surface patch that results in the reversed vectors along one edge. Is there an error in surfnorm? Can I predict when this will happen so I can fix it with subsequent code?
x = [ -3.2851 -3.2718 -3.1598; -3.2851 -3.2718 -3.1598; -3.2851 -3.2718 -3.1598];
y = [ 169.1481 169.1148 168.8310; 169.1481 169.1148 168.8310; 169.1481 169.1148 168.8310];
z = [ -1 -1 -1; 0 0 0; 1 1 1];
figure(1)
surfnorm(x,y,z)

Best Answer

The surfnorm function requires the Z input to be at least a 3x3 matrix because it uses a Taylor Series to predict the next surface point beyond the given inputs.
In this particular case, the surface mesh boundaries are predetermined, and the mesh is coarse. The combination of these two characteristics can create a very large 2nd derivative of the surface in the Taylor Series Prediction. In this case, the extended boundary was actually folded back inside the input surface.
I don't like altering built-in Matlab functions, but I fixed the problem by removing the 2nd derivative from the Taylor Series prediction...
Replace lines 81-87 of the surfnorm function with the following:
% % Expand x,y,z so interpolation is valid at the boundaries.
% xx = [3*xx(1,:)-3*xx(2,:)+xx(3,:);xx;3*xx(m,:)-3*xx(m-1,:)+xx(m-2,:)];
% xx = [3*xx(:,1)-3*xx(:,2)+xx(:,3),xx,3*xx(:,n)-3*xx(:,n-1)+xx(:,n-2)];
% yy = [3*yy(1,:)-3*yy(2,:)+yy(3,:);yy;3*yy(m,:)-3*yy(m-1,:)+yy(m-2,:)];
% yy = [3*yy(:,1)-3*yy(:,2)+yy(:,3),yy,3*yy(:,n)-3*yy(:,n-1)+yy(:,n-2)];
% zz = [3*zz(1,:)-3*zz(2,:)+zz(3,:);zz;3*zz(m,:)-3*zz(m-1,:)+zz(m-2,:)];
% zz = [3*zz(:,1)-3*zz(:,2)+zz(:,3),zz,3*zz(:,n)-3*zz(:,n-1)+zz(:,n-2)];
%% GJE Alteration
% Expand x,y,z so interpolation is valid at the boundaries.
xx = [xx(1,:)+ (xx(1,:)-xx(2,:)) ;xx; xx(m,:)+ (xx(m,:)-xx(m-1,:))];
xx = [xx(:,1)+ (xx(:,1)-xx(:,2)) ,xx, xx(:,n)+ (xx(:,n)-xx(:,n-1))];
yy = [yy(1,:)+ (yy(1,:)-yy(2,:)) ;yy; yy(m,:)+ (yy(m,:)-yy(m-1,:))];
yy = [yy(:,1)+ (yy(:,1)-yy(:,2)) ,yy, yy(:,n)+ (yy(:,n)-yy(:,n-1))];
zz = [zz(1,:)+ (zz(1,:)-zz(2,:)) ;zz; zz(m,:)+ (zz(m,:)-zz(m-1,:))];
zz = [zz(:,1)+ (zz(:,1)-zz(:,2)) ,zz, zz(:,n)+ (zz(:,n)-zz(:,n-1))];
%%
Regards, Gabe