cvx 官网教程

官网有一个13分钟的视频教程

http://cvxr.com/news/2014/02/cvx-demo-video/

例一:

cvx_begin

variables x y    %定义几个变量,变量之间是空格

minimize ((x+y+3)^2)  %目标函数

y>=0    %加入约束

cvx_end

运行后,x和y的值就会改变,并且满足目标和约束

cvx_status    %问题解决状态—solved,infeasible...

cvx_optval    %目标函数的值,非常小的时候就算是基本上等于零


可以把cvx放到 matlab 代码的任何地方使用

只能解决凸问题,非凸(仿射的约束?)虽然会解决,但结果可能都是0。


例二:

%矩阵的问题

A=randn(100,30);

b=randn(100,1);

cvx_begin

variables x(30)    %x是向量型的变量,长度30

x>=0    %约束

sum(x) == 1    %约束,用的双等号

minimize (norm(A*x-b))    %目标函数。结果为向量。所以norm(ans) =sum(|ans|^2)^(1/2),即平方和开方。

cvx_end


例三:

cvx_begin

variables C(3,) symmetric

diag(C) == 1    % 三个都是1

C(1,2) == 0.6    %约束

C(2,3) ==-0.30    %约束

C == semidefinite (3)    %半正定...

maximize (C(1,3))    %目标函数

cvx_end


这个是官网库里的例子

http://web.cvxr.com/cvx/examples/cvxbook/Ch04_cvx_opt_probs/html/chebyshev_center_2D.html

%多面体的切比雪夫中心

% Generate the input data

a1 = [ 2;  1];%这四个是斜率

a2 = [ 2; -1];    

a3 = [-1;  2];

a4 = [-1; -2];

b = ones(4,1);

% Create and solve the model

cvx_begin

variabler(1)   %半径

variable x_c(2)   %圆心位置

maximize ( r )    %最大的圆?看结果四条线都切了。大概是因为对称,所以能四边都相切。

a1'*x_c + r*norm(a1,2) <= b(1);    %总之多面体是给出了

a2'*x_c + r*norm(a2,2) <= b(2);    %’:转置

    a3'*x_c + r*norm(a3,2) <= b(3);    %感觉2范数是个比较方便的写法

    a4'*x_c + r*norm(a4,2) <= b(4);

cvx_end

点到直线的距离公式

    %所以约束条件是半径 r < 圆心到线的距离

% Generate the figure

x = linspace(-2,2);

theta = 0:pi/100:2*pi;

plot( x, -x*a1(1)./a1(2) + b(1)./a1(2),'b-');

holdon

plot( x, -x*a2(1)./a2(2) + b(2)./a2(2),'b-');

plot( x, -x*a3(1)./a3(2) + b(3)./a3(2),'b-');

plot( x, -x*a4(1)./a4(2) + b(4)./a4(2),'b-');

plot( x_c(1) + r*cos(theta), x_c(2) + r*sin(theta),'r');

plot(x_c(1),x_c(2),'k+')

xlabel('x_1')

ylabel('x_2')

title('Largest Euclidean ball lying in a 2D polyhedron');

axis([-1 1 -1 1])    %坐标范围

axisequal


你可能感兴趣的:(cvx 官网教程)