怎样用matlab求一元线性函数极值
发布网友
发布时间:2022-04-22 05:24
我来回答
共2个回答
热心网友
时间:2023-05-18 07:34
clear; %%%%% 清变量
clc; %%%%% 清屏幕
syms x; %%%% 定变量
f = sqrt(5^2+(8-x)^2)*28.8+sqrt(15^2+(5+x)^2)*7.2; %%%% 变量表达式
y = @(x) sqrt(5^2+(8-x)^2)*28.8+sqrt(15^2+(5+x)^2)*7.2; %%%% 句柄函数
df = diff(f); %%%% 求微分
xz = solve(df); %%%% 求极值点
[m,n] = size(xz); %%%% 求极值点个数
d2f = diff(f,2); %%%% 求二阶微分,以判断极大极小
for ii = 1:n %%%% 对每个极值点进行判断
z(ii) = limit(d2f,x,xz(ii)); %%%%% 求二阶微分在极值点的极限
%temp = vpa(z(ii));
temp = double(z(ii)); %%%%% 转成数值判断
if temp>0 %%%%% 二阶微分大于零,是极小值点
fprintf('find a minimum point x = %f,and the minimum value is f(%f) = %f\n',temp,temp,y(temp));
elseif temp<0 %%%%% 二阶微分小于零,是极大值点
fprintf('find a maxima point x = %f,and the maxima value is f(%f) = %f\n',temp,temp,y(temp));
end
end
结果:
find a minimum point x = 5.770419,and the minimum value is f(5.770419) = 290.624828
小做修改了一下,不用函数句柄,直接用符号计算,可以更精确点:
clear; %%%%% 清变量
clc; %%%%% 清屏幕
syms x; %%%% 定变量
f = sqrt(5^2+(8-x)^2)*28.8+sqrt(15^2+(5+x)^2)*7.2; %%%% 变量表达式
%y = @(x) sqrt(5^2+(8-x)^2)*28.8+sqrt(15^2+(5+x)^2)*7.2; %%%% 句柄函数
df = diff(f); %%%% 求微分
xz = solve(df); %%%% 求极值点
[m,n] = size(xz); %%%% 求极值点个数
d2f = diff(f,2); %%%% 求二阶微分,以判断极大极小
for ii = 1:n %%%% 对每个极值点进行判断
z(ii) = limit(d2f,x,xz(ii)); %%%%% 求二阶微分在极值点的极限
%temp = vpa(z(ii));
temp = double(z(ii)); %%%%% 转成数值判断
if temp>0 %%%%% 二阶微分大于零,是极小值点
fmin = double(limit(f,x,xz));
fprintf('find a minimum point x = %f,and the minimum value is f(%f) = %f\n',temp,temp,fmin);
elseif temp<0 %%%%% 二阶微分小于零,是极大值点
fmax = doubel(limit(f,x,xz));
fprintf('find a maxima point x = %f,and the maxima value is f(%f) = %f\n',temp,temp,fmax);
end
end
结果:
find a minimum point x = 5.770419,and the minimum value is f(5.770419) = 285.043134
结果验证,你可以自己画个图看看,在命令框输入以下命令即可:
>> syms x;
>> f = sqrt(5^2+(8-x)^2)*28.8+sqrt(15^2+(5+x)^2)*7.2;
>> ezplot(f,[-10,10])
热心网友
时间:2023-05-18 07:35
matlab?太猛了点吧