Re: [问题] C++ 矩阵问题

楼主: celestialgod (天)   2014-04-23 22:27:30
分享一下我把matlab转成C++的经验
希望对原PO有帮助
我一开始就打算使用额外的函式库帮我做矩阵的运算
我先使用Eigen library
我先从下面的对照表看起
http://eigen.tuxfamily.org/dox-devel/AsciiQuickReference.txt
先看我大概需要哪些函数 并且先纪录下来
然后画出架构,从资料下手,从input开始逐步往下转
但是无法避免的是你可能需要自己写函数来辅助工作
我是这样去写:
MatrixXd function_name(const MatrixXd& input1, const MatrixXd& input2, ...)
只是C++很多时候不如MATLAB方便
必须多注意,怎样避免复制资料,我一开始写常常乱assign新的变量(囧)
我后来转去用armadillo 我认为它真的根matlab比较接近
只是需要好的blas, lapack库帮助,不然效能真的不佳
命令参考:
http://arma.sourceforge.net/docs.html#syntax
可以看出armadillo跟MATLAB比较接近
函数写法:
Mat<double> function_name(const Mat<double>& input1, const Mat<double>& input2,..)
PS: Mat<double> = mat
其他部份基本上同eigen,这两者都可以用template去构筑generic function
简单比较两个与MATLAB的指令 (排版有点乱,请见谅)
c: constant, A:n by n matrix, B: n by p matrix, V: n by 1 vector
MATLAB Eigen Armadillo
c*A c*A A.array()*c c*A
A*B A*B A*B A*B
A.*B A*B A.array()*B.array() A%B
column sum sum(A,1) A.colwise().sum() sum(A,0)
column mean mean(A,1) (A.array() / A.rows()).colwise().sum() mean(A,0)
inverse inv(A) A.inverse() A.i()
solve linear A\B A.solve(B) A.solve(B)
equation PS:Eigen提供数种解法可选
take diagonal diag(A) A.diagonal() A.diag()
elements
row bind [A;B'] block(?) join_cols(A,B.t())
randomly randperm(V) rand_shuffle(V.data(), V.data()+V.size()) shuffle(V)
permute elements
?????? V(V<0) = 0 (V.array() < 0).select(0, V)
arma::max(V, zeros<mat>(V.n_rows, 1))
colwise min min(A,[],1) A.colwise().min() min(A,0)
location of [tmp,loc_r] = min(A) unsigned int loc_c, loc_w uword loc_c, loc_r
minimum [~,loc_c] = min(tmp) A.minCoeff(&loc_r, &loc_c) A.min(loc_c,loc_r)
A(loc_r(loc_c),loc_c) is min A(loc_r,loc_c) is min 同左
element-wise comparison就不提...以上这些是我比较常用到的指令
个人觉得armadillo提供比较多轻易使用的函数,你可以自由选择你喜欢的函式库
顺便一提,我的测试是 (以下测试都有使用openmp)
armadillo with openblas比Eigen还快
armadillo with intel MKL 跟 Eigen with intel MKL 基本上armadillo快一点
armadillo默认(不支援openmp) 比 Eigen慢非常多
以上提供你转换code的参考
另外,可以偷问Eigen or armadillo有类似diff的函数吗XDD
楼主: celestialgod (天)   2014-04-23 22:33:00
如果是写MEX function,则arma有比提供比较好的API
作者: damody (天亮damody)   2014-04-24 01:19:00
推~我是因为我的问题都是sparse matrix所以一定要用Eigendiff 我有实作过 但eigen 没看过https://damody.googlecode.com/files/L0smoothing.7z这里面有diff
楼主: celestialgod (天)   2014-04-24 08:13:00
armadillo也有sparse matrix喔~~

Links booklink

Contact Us: admin [ a t ] ucptt.com