Filter löschen
Filter löschen

How to use fminsearch for a function converted from symbolic expression

3 Ansichten (letzte 30 Tage)
Hello,
I am trying to fit a plane to a set of data. I'd like to write my own function with fminsearch function.
I created the objective function using symbolic, and then I convert the symbolic expression to a function handle using "matlabFunction". Finally, I pass the function handle to the fminsearch function. However, Matlab reports "Not enough input arguments" How do I fix this?
My code is as the following
% I have 36 3D points. I'd like to use a plane to fit them
% Pcr_th is a 36-3 matrix that contains the point coordinates, the columns represent X, Y and Z coordinates
syms A B C D
sum_sqd = 0;
for i = 1:36
d = ( A*Pcr_th(i,1) + B*Pcr_th(i,2) +C*Pcr_th(i,3) + D) / (sqrt(A*A+B*B+C*C));
sqd = d*d;
sum_sqd = sum_sqd + sqd;
end
% find the centroid
ctroid_x = sum(Pcr_th(i,1))/36;
ctroid_y = sum(Pcr_th(i,2))/36;
ctroid_z = sum(Pcr_th(i,3))/36;
% initial guess for D
Dint = -(ctroid_x+ ctroid_y + ctroid_z);
% Create the objective function
fun = matlabFunction(sum_sqd,'vars',[A,B,C,D]);
intg = [1, 1, 1, Dint]; % this is the initial guess.
a = fminsearch (fun, intg) % This reports Not enough input arguments. And error in fun=matlabFunction...

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 8 Jun. 2020
fun = matlabFunction(sum_sqd, 'vars', {[A,B,C,D]});
When you pass in a vector of variables for the 'vars' option, then matlabFunction uses one input parameter for each variable.
When you pass in a cell array for the 'vars' option, then matlabFunction uses one input parameter for each element of the cell array, packing all of the variables present in that one entry into a single parameter.

Weitere Antworten (0)

Produkte


Version

R2018b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by