How to use fminsearch for a function converted from symbolic expression

조회 수: 3 (최근 30일)
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...

채택된 답변

Walter Roberson
Walter Roberson 2020년 6월 8일
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.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Choose and Parameterize Blocks에 대해 자세히 알아보기

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by