The ‘trick’ here is to create a matrix of your ‘x’ and ‘y’ data vectors and give them to your objective function as a single argument. The objective function can then refer to the appropriate columns of that matrix to use ‘x’ and ‘y’ correctly in your equation. I created random ‘x’, ‘y’, and ‘z’ vectors to test my code, so substitute your data for them. My code would otherwise not change. The estimated parameters are the ‘B’ output of the fminsearch call, the second ‘resnorm’ output being the norm of the residuals. (The ‘resnorm’ output is not necessary, but is helpful in assessing how good the fit is.)
The Code —
z_fit = @(b, xy) b(1) .* xy(:,2).^b(2) .* exp(b(3) .* xy(:,1));
x = randi(99, 1, 10);
y = randi(99, 1, 10);
z = randi(99, 1, 10);
xy = [x(:), y(:)];
NCF = @(b) norm(z - z_fit(b,xy));
B0 = [1; 2; 3];
[B,resnorm] = fminsearch(NCF, B0);
You can plot the result using scatter3 or stem3 for your data, and plot3 for the objective function fit. Use the hold function to plot them on the same axes, and grid on to show the grid lines.
Best Answer