step1:克隆代码并编译
编译的前提是已经安装好MinGW64
# 使用镜像加速
git clone https://gitclone.com/github.com/stevengj/nloptcd nlopt
mkdir build
cd build
cmake -G="MinGW Makefiles" ..
cmake --build .# 注意此处博主在mingw安装目录将mingw32-make重命名成了make
make install
nlopt将被自动安装至C:/Program Files (x86)/nlopt
下。
step2:编译mex文件
- 将nlopt项目目录下的
nlopt\src\octave\nlopt_optimize-mex.c
拷贝到C:\Program Files (x86)\nlopt\lib\matlab
,并重命名为nlopt_optimize.c
- 在nlopt安装目录下,将
include\nlopt.h
和bin\libnlopt.dll
拷贝到lib\matlab
目录下 - matlab工作目录切至
lib\matlab
,终端中执行:mex -v nlopt_optimize.c ../libnlopt.dll.a
- 将
C:\Program Files (x86)\nlopt\lib\matlab
添加到matlab路径中
至此已完成Nlopt在matlab中的配置
step3:测试
clc,clear,close allopt.algorithm = NLOPT_LD_MMA;
opt.lower_bounds = [-inf, 0];
opt.min_objective = @myfunction;
opt.fc = { (@(x) myconstraint(x,2,0)), (@(x) myconstraint(x,-1,1)) };
opt.fc_tol = [1e-8, 1e-8];
opt.xtol_rel = 1e-4;
[xopt, fmin, retcode] = nlopt_optimize(opt, [1.234 5.678])% 目标函数
function [val, gradient] = myfunction(x)val = sqrt(x(2));if (nargout > 1)gradient = [0, 0.5 / val];end
end% 约束函数
function [val, gradient] = myconstraint(x,a,b)val = (a*x(1) + b)^3 - x(2);if (nargout > 1)gradient = [3*a*(a*x(1) + b)^2, -1];end
end
参考链接:
- https://nlopt.readthedocs.io/en/latest/NLopt_Matlab_Reference/
- https://blog.csdn.net/jialing678/article/details/120415359