hey you
rng控制随机数生成器
语法:
rng(seed)
rng(seed,generator)
s=rng
说明:
rng函数控制全局流
决定rand,randi,randn,randperm函数如何产生一系列随机数
generator指定要使用的随机数生成器的类型
默认'default' 种子0,梅森旋转
rng('default')
rng(0,'twister')
'shuffle' :根据当前时间初始化生成器
generator:随机数算法
'twister' 梅森旋转
'simdTwister' 面向SIMD的快速梅森旋转
'combRecursive' 组合多递归
'multFibonacci' 乘法滞后Fibonacci
'philox' 执行10轮的Philox 4*32生成器
'threefry' 执行20轮的Threefry 4*64生成器
function [f,g]=mengte(x)
f=x(1)^2+x(2)^2+3*x(3)^2+4*x(4)^2+2*x(5)^2-8*x(1)-2*x(2)-3*x(3)-x(4)-2*x(5);
g=[sum(x)-400
x(1)+2*x(2)+2*x(3)+x(4)+6*x(5)-800
2*x(1)+x(2)+6*x(3)-200
x(3)+x(4)+5*x(5)-200];
end
clc,clear
% x0=rand(1,5);
%rand('state',sum(clock));
rng('shuffle');
p0=0;
tic;
for i=1:10^6
x=randi([0,99],1,5);
[f,g]=mengte(x);
if all(g<=0)
if p0<f
x0=x;p0=f;
end
end
end
x0,p0
toc
第三章 非线性规划
3.2 无约束问题的matlab解法
符号解
clc,clear
syms x y
f=x^3-y^3+3*x^2+3*y^2-9*x;
df=jacobian(f);
d2f=jacobian(df);
[xx,yy]=solve(df);
xx=double(xx); yy=double(yy);
for i=1:length(xx)
a=subs(d2f,{x,y},{xx(i),yy(i)});
b=eig(a);
f=subs(f,{x,y},{xx(i),yy(i)});
f=double(f);
if all(b>0)
fprintf('(%f,%f)是极小值点,对应的极小值为%f\n',xx(i),yy(i),f);
elseif all(b<0)
fprintf('(%f,%f)是极大值点,对应的极大值为%f\n',xx(i),yy(i),f);
elseif any(b>0)&& any(b<0)
fprintf('(%f,%f)不是极值点\n',xx(i),yy(i));
else
fprintf('无法判断(%f,%f)是否是极值点\n',xx(i),yy(i));
end
end
数值解
clc,clear
f=@(x) x(1)^3-x(2)^3+3*x(1)^2+3*x(2)^2-9*x(1);
g=@(x) -f(x);
[xy1,z1]=fminunc(f,rand(2,1))
[xy2,z2]=fminunc(g,rand(2,1));
xy2,z2=-z2
注:fminsearch只能求给定的初值附近的一个极小值点
function [f,g]=fun3(x)
f=100*(x(2)-x(1)^2)^2+(1-x(1))^2;
g=[-400*x(1)*(x(2)-x(1)^2)-2*(1-x(1));
200*(x(2)-x(1)^2)];
end
function [f,df,d2f]=fun4(x)
f=100*(x(2)-x(1)^2)^2+(1-x(1))^2;
df=[-400*x(1)*(x(2)-x(1)^2)-2*(1-x(1));
200*(x(2)-x(1)^2)];
d2f=[-400*x(2)+1200*x(1)^2+2,-400*x(1)
-400*x(1),200];
end
clc,clear
options=optimset('GradObj','on');
[x,y]=fminsearch('fun3',rand(1,2),options)
clc,clear
options=optimset('GradObj','on');
[x,y]=fminsearch(@fun4,rand(1,2),options)
3.2.3 求函数的零点和方程组的解
求多项式的零点。
clc,clear
xishu=[1 -1 2 -3];
x0=roots(xishu)
syms x %符号解
x0=solve(x^3-x^2+2*x-3);
x0=vpa(x0,5)
y=@(x)x^3-x^2+2*x-3; %数值解,,,只能求给定初始值附近的一个零点
x=fsolve(y,rand)
方程组
syms x y %符号解
[x,y]=solve(x^2+y-6,y^2+x-6)
f=@(x) [x(1)^2+x(2)-6;x(2)^2+x(1)-6]; %数值解
xy=fsolve(f,rand(2,1))