= meshgrid(linspace(min(a), max(a), ngrid). To make an interpolation over some regular grid, you can do like so: ngrid = 20 Which seems to have numerical problems for the limited dataset you gave. Similarly, you can do a second order fit: %second order fit %least square solution of z = M * k1, so z = k1(1) + k1(2) * x + k1(3) * y There might be some better functions on the file-exchange, but one way to do it by hand is this: x = a(:) %make column vectors Zz = x2fx(, 'quadratic') * C įinally there is an excellent function polyfitn on the File Exchange by John D'Errico that allows you to specify all kinds of polynomial orders and terms involved: model = polyfitn(data(:,1:2), data(:,3), 2) There is also a helper function x2fx in the Statistics Toolbox that helps in building the design matrix for a couple of model orders: C = x2fx(data(:,1:2), 'quadratic') \ data(:,3) We can do this manually: % best-fit quadratic curveĬ = \ data(:,3) Say we want to fit a quadratic model with constant, linear, interaction, and squared terms (1, x, y, xy, x^2, y^2). 'FaceColor','interp', 'EdgeColor','b', 'FaceAlpha',0.2)Īs was mentioned, we can get higher-order polynomial fitting by adding more terms to the independent variables matrix (the A in Ax=b). Next we visualize the result: % plot points and surface % or expressed using matrix/vector product % evaluate it on a regular grid covering the domain of the data There is a solution page by MathWorks describing the process.Īs an example, let's start with some random data: % some 3d pointsĭata = mvnrnd(,, 50) Īs showed, by constructing the desired design matrix, you can use mldivide or pinv to solve the overdetermined system expressed as Ax=b: % best-fit planeĬ = \ data(:,3) % coefficients
The following example shows how to use meshgrid to create a surface plot of a function.To fit a curve onto a set of points, we can use ordinary least-squares regression.
Meshgrid is limited to two- or three-dimensional Cartesian space. That is, the statementīecause of this, meshgrid is better suited to problems in two- or three-dimensional Cartesian space, while ndgrid is better suited to multidimensional problems that aren't spatially based. The meshgrid function is similar to ndgrid except that the order of the first two input and output arguments is switched. Produces three-dimensional arrays used to evaluate functions of three variables and three-dimensional volumetric plots.
The rows of the output array X are copies of the vector x columns of the output array Y are copies of the vector y. Transforms the domain specified by vectors x and y into arrays X and Y, which can be used to evaluate functions of two variables and three-dimensional mesh/surface plots. Generate X and Y matrices for three-dimensional plots Meshgrid (MATLAB Functions) MATLAB Function Reference