军人服务社管理规定:matlab 编程

来源:百度文库 编辑:杭州交通信息网 时间:2024/05/02 07:43:29
求x*sinx在[-10,10]上的所有极值,用matlab编程
没这么复杂吧?
把关键的地方写出来就行

matlab源程序:

function [yy,yf,ymax]=test(a,b)
if ~(nargin==0 | nargin==2)
error('输入参数个数错误');
end
if nargin==0
a=-10;b=10;
end
clc;
if nargout>3
error('输出参数不能超过3个');
end
step=(b-a)/200;
stat=a;y=[];
eps=1.0e-6;
te=ff(stat);
while te < a & stat <= b
stat=stat+step;
te=ff(stat);
end
if te > b | stat > b
disp('该函数在 [-10,10] 内无极值点');
return
end
i=1;
stat=stat+step;
res(i)=te;
te=ff(stat);
while stat<=b
if ~insets(te,res)%判断找出的点是不是已经存在
i=i+1;res(i)=te;stat=stat+step;
else
stat=stat+step;
end
te=ff(stat);
end
n=0;
for i=1:length(res)
if res(i)>=a & res(i) <=b
n=n+1;y(n)=res(i);
end
end
res=[];n0=0;
for i=1:n
if checkss(y(i))
n0=n0+1;
res(n0)=y(i);
end
end
n=n0;y=[];y=sort(res);
outs=[1:n;y;temm(y)];
disp(['共发现 ',num2str(n),' 个极值点:']);
disp('编号 x y');
fprintf(1,'%2d %9.6f %9.6f\n',outs);
if nargout>=1
yy=y';
end

if nargout>=2
yf=temm(y)';
end
if nargout==3
ymax=max([yf;temm(a);temm(b)]);
end
yyf=temm(y)';
ymmin=min([yyf;temm(a);temm(b)]);
ymmax=max([yyf;temm(a);temm(b)]);
x0=a:0.01:b;
y0=temm(x0);
plot(x0,y0,'-b','linewidth',1.3,'markersize',4);
hold on;
axis([a-0.5 b+0.5 ymmin-0.5 ymmax+0.5]);
title(['共发现 ',num2str(n),' 个极值点(红点)']);
plot(y',yyf,'r.','linewidth',2,'markersize',16);
for t=1:n
text(y(t),yyf(t),num2str(t));
end
%grid on;
hold off;

function y=ff(x0)
%定义函数
options = optimset('Display','off');
y=fsolve(@dtemm,x0,options);

function y=temm(x)
for i=1:length(x)
y(i)=x(i)*sin(x(i));
end

function y=insets(te,res)
eps=1.0e-5;
for i=1:length(res)
if abs(te-res(i))<eps
y=1;return;
end
end
y=0;

function y=checkss(x)
%检查稳定点x是否是极值点
rd=1.0e-4;
y0=temm(x);
xx=(x-rd):rd/10:(x+rd);
y1=temm(xx);
y=1;
if y0>temm(x-rd)
for i=1:length(xx)
if y0<y1(i)
y=0;return;
end
end
else
for i=1:length(xx)
if y0>y1(i)
y=0;return;
end
end
end

function y=dtemm(x)
syms a;
yt=diff(temm(a));
y=subs(yt,'a',x);

运行结果:
共发现 7 个极值点:
编号 x y
1 -7.978666 7.916727
2 -4.913180 -4.814470
3 -2.028758 1.819706
4 -0.000000 0.000000
5 2.028758 1.819706
6 4.913180 -4.814470
7 7.978666 7.916727

求极值直接求偏导数为零不就可以了吗?