Problem using fminbnd function

3次观看(最近30天)
Milena Peixoto Rodrigues
Milena Peixoto Rodrigues 上23 Sep 2021
Answered: Alan Weiss 上24 Sep 2021
The question gives the equation , and asks to generate a user-defined function for n=2 and 6; with n being the input vector and r being the output vector. The r value ranges from 1 to 5. It also asks to graph the U(r) curve for each n on the same plot and mark the points of the minimum.
I wrote this code:
functionr_min = Quards_4_15(n,r1,r2)
closeall
U=@(x)4*((1/x).^(2.*n) - (1/x).^(n));
options=optimset('Display','iter');
[r_min,u_min] = fminbnd(u,r1,r2,options);% Error Occurrence Line
rg=linspace(r1,r2);
Ug=U(rg);
plot(rg,Ug,r_min,U_min,'o')
grid
xlabel('Distance Intermolecular r*')
ylabel('Potential Energy U')
title(Lennard-Jones-type无量纲的)
legend('function U','minimum r')
Matlab reports the following error:
问题_4_15([2 6],1,5)
错误using fminbnd (line 238)
用户supplied objective function must return a scalar value.
错误in Problem_4_15 (line 5)
[r_min,u_min] = fminbnd(u,r1,r2,options);
FMINBND功能代码的一部分,其中显示第238行:
% Check that the objective value is a scalar
ifnumel(fx) ~= 1
错误('MATLAB:fminbnd:NonScalarObj',...% Line 238
getString(message('MATLAB:optimfun:fminbnd:NonScalarObj')));
end
How can I solve this problem to make the code work?
Thanks in advance.

Answers (1)

Alan Weiss
Alan Weiss 上24 Sep 2021
All optimization solvers require that the objective function return a scalar value. You need to write your objective function in a way that it returns a scalar, not a vector or an array.
If you are trying to solve for a variety of parameter values, well, you will have to write a loop and solve for one parameter value at a time.
Alan Weiss
MATLAB mathematical toolbox documentation

下载188bet金宝搏


发布

R2020b

Community Treasure Hunt

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

开始狩猎!