NLopt与犰狳数据 [英] NLopt with Armadillo data

查看:129
本文介绍了NLopt与犰狳数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

NLopt目标函数如下所示:

The NLopt objective function looks like this:

double myfunc(const std::vector<double> &x, std::vector<double> &grad, void *my_func_data)

x是要优化的数据,grad是梯度的向量,my_func_data保存其他数据.

x is the data being optimized, grad is a vector of gradients, and my_func_data holds additional data.

我有兴趣提供犰狳矩阵A和B来使* my_func_data无效.

我摆弄着Armadillo的成员函数

I fiddled with Armadillo's member functions

mat A(5,5);
mat B(5,5);
double* A_mem = A.memptr();
double* B_mem = B.memptr();

这给了我指向矩阵A和B的指针.我正在考虑定义另一个指向这些指针的指针:

which gives me a pointers to the matrices A and B. I was thinking of defining another pointer to these pointers:

double** CombineMat;
int* Arow = A.n_rows; int* Acols = A.n_cols; //obtain dimensions of A
int* Brows = B.n_rows; int* Bcols = B.n_cols; // dim(B)
CombineMat[0] = A_mem; CombineMat[1] = Arows; CombineMat[2] = Acols;
CombineMat[3] = B_mem; CombineMat[4] = Brows; CombineMat[5] = Bcols;

,然后将* CombineMat作为my_func_data传递.

and then passing *CombineMat as my_func_data.

  1. 这是这样做的方法吗?看起来笨拙...
  2. 一旦通过CombineMat,当我在myfunc中时,如何将void类型重新转换为可用的类型?

答案

我在此处的帮助下回答了自己的问题.

I answered my own question with help from here.

mat A(2,2);
A << 1 << 2 << endr << 3 << 4;

mat B(2,2);
B << 5 << 6 << endr << 7 << 8;

mat C[2];
C[0] = A;
C[1] = B;

opt.set_min_objective(myfunc, &C);

一旦进入myfunc,就可以将C中的数据转换回Armadillo矩阵,如下所示:

Once inside myfunc, the data in C can be converted back to Armadillo matrices like this:

mat* pC = (mat*)(my_func_data);
mat A = pC[0];
mat B = pC[1];

推荐答案

您还可以使用Armadillo的多维数据集类("3D矩阵"或3阶张量).

You can also use Armadillo's Cube class ("3D matrix", or 3-rd order tensor).

多维数据集中的每个切片都只是一个矩阵.例如:

Each slice in a cube is just a matrix. For example:

cube X(4,5,2);

mat A(4,5);
mat B(4,5);

X.slice(0) = A;  // set the individual slices
X.slice(1) = B;

mat& C = X.slice(1); // get the reference to a matrix stored in a cube

这篇关于NLopt与犰狳数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆