function [x_f, y_f, z_f, mse_f, max_error] = find_best_table_2d(...
x_0, y_0, z_0, ...
n_x, n_y, ...
method)
%% find_best_table_2d
%
% This function finds the best way to reduce the size of a table to the
% specified number of points. That is, suppose you had a table of
% 100-by-10,000 points, but wanted to find the closest 9-by-10 table. This
% function would find what 9-by-10 points best represent the original
% table. This is accomplished using traditional constrained optimization
% techniques to best fit a table with the specified dimensions. "Goodness"
% will be measured by the difference between the original table and the new
% table sampled at the original data points. See find_best_table_demo.m for
% examples.
%
% Inputs:
% x_0 Array of values for the first independent variable
% y_0 Array of values for the second indepdendent variable
% z_0 Matrix of values for the dependent variable for all x_0 and y_0
% using meshgrid-style syntax (e.g., z_0(2, 3) corresponds to
% x_0(3) and y_0(2)).
% n_x Number of divisions of the first independent variable in output
% n_y Number of divisions of the second independent variable in output
% method Interpolation method to use, e.g., 'linear' (see help interp2)
%
% Outputs:
% x_f Best division of first independent variable found
% y_f Best division of second independent variable found
% z_f Resulting fit of z_0 on x_f and y_f
% mse_f Mean square error of final table
%
% This builds off of work by Richard Willey, Stuart Kozola, Eric Johnson,
% Sarah Zaranek, and Peter Maloney at The MathWorks, Inc.
%
% Requires the Optimization Toolbox (TM).
% Supports the Parallel Computing Toolbox (TM).
%
% Tucker McClure @ The MathWorks
% Copyright 2013 The MathWorks, Inc.
% Do some quick error checking and set defaults for arguments.
if nargin == 5
method = 'linear';
elseif nargin > 6 || nargin < 5
error('Incorrect number of arguments.');
end
% Make sure numbers make sense.
if n_x < 3 || n_y < 3
error(['Table must be at least 3x3 (otherwise, it represents ' ...
'only the corners, so there''s nothing to solve.\n']);
end
% Just call the n-dimensional version. This file is here for backwards
% compatibility.
[x_fs, z_f, mse_f, max_error] = find_best_table_nd({x_0, y_0}, ...
z_0', ...
[n_x, n_y], ...
method);
% n-D interpolation uses ndgrid format; 2d used meshgrid format at its
% release, so we'll preserve that for compatibility.
z_f = z_f';
% Separate the x and y breakpoints.
x_f = x_fs{1};
y_f = x_fs{2};
end