R语言学习RcppEigen进行矩阵运算

目录
  • 创建cpp文件
    • 代码示例
  • 其他矩阵操作
    • 命名
    • 基础用法
    • 定义矩阵
    • 对矩阵的一些基础操作1
    • 基础操作2
    • 矩阵基础运算1
    • 矩阵基础运算2
    • 求最小最大值、迹等
    • 点乘等
    • 特征值与特征向量
    • 形式转换
    • 矩阵初始化0
    • Map等操作
    • 求解Ax = b

前面我们介绍了一些基本的Rcpp的用法:让你的R代码更快——Rcpp入门,但用基础的Rcpp来进行矩阵运算还是非常麻烦,没有现成的函数来让我们使用。

这时我们就想到:是否可以调用别的库来解决矩阵运算的一些问题呢?这就需要我们的RcppEigen包,也就是C++中的Eigen库。

这些矩阵的运算在进行模拟时会时常遇到,所以可以说是非常重要的一项技能,下面我们就给予一个现有的对矩阵处理的代码来说明其用法。

创建cpp文件

其创建方式可以参考上篇博客:让你的R代码更快——Rcpp入门

代码示例

然后我们定义一个

来做矩阵乘法并求其迹(trace)的函数。

// [[Rcpp::depends(RcppEigen)]]
#include <RcppEigen.h>
using namespace Eigen;
using namespace std;

//[[Rcpp::export]]
double myfun (MatrixXd X, MatrixXd Y) {
  double Z;

  Z = (X.adjoint() * Y).trace();
  cout << Z << endl;

  return Z;
}

前三行表示载入Eigen

// [[Rcpp::depends(RcppEigen)]]
#include <RcppEigen.h>
using namespace Eigen;

里面的转置函数adjoint(),求迹函数trace(),都需要用到这个库,如果不使用命名空间Eigen后面库里面就要这样用Eigen::adjoint()Eigen::trace()

后面我们使用using namespace std;则是因为cout需要用到,这个可以在运行函数的时候展现我们的中间变量,也是一个比较有用的操作,当然如果不需要的话,就可以不用命名变量空间:std

下面就是我们的函数:

//[[Rcpp::export]]
double myfun (MatrixXd X, MatrixXd Y) {
  double Z;

  Z = (X.adjoint() * Y).trace();
  cout << Z << endl;

  return Z;
}

//[[Rcpp::export]]为我们需要导出到R中的时候需要添加,double型的矩阵在Eigen中命名为MatrixXd,整型矩阵为MatrixXi;类似,对应的向量命名方式为:VectorXdVectorXi

里面的内容就是我们按照公式敲的函数。

下面我们介绍一些Eigen库中的其它一些矩阵操作。

其他矩阵操作

这部分原文:A simple quickref for Eigen

命名

Matrix<double, 3, 3> A;               // Fixed rows and cols. Same as Matrix3d.
Matrix<double, 3, Dynamic> B;         // Fixed rows, dynamic cols.
Matrix<double, Dynamic, Dynamic> C;   // Full dynamic. Same as MatrixXd.
Matrix<double, 3, 3, RowMajor> E;     // Row major; default is column-major.
Matrix3f P, Q, R;                     // 3x3 float matrix.
Vector3f x, y, z;                     // 3x1 float matrix.
RowVector3f a, b, c;                  // 1x3 float matrix.
VectorXd v;                           // Dynamic column vector of doubles
double s;

基础用法

// Basic usage
// Eigen          // Matlab           // comments
x.size()          // length(x)        // vector size
C.rows()          // size(C,1)        // number of rows
C.cols()          // size(C,2)        // number of columns
x(i)              // x(i+1)           // Matlab is 1-based
C(i,j)            // C(i+1,j+1)       //

A.resize(4, 4);   // Runtime error if assertions are on.
B.resize(4, 9);   // Runtime error if assertions are on.
A.resize(3, 3);   // Ok; size didn't change.
B.resize(3, 9);   // Ok; only dynamic cols changed.

A << 1, 2, 3,     // Initialize A. The elements can also be
     4, 5, 6,     // matrices, which are stacked along cols
     7, 8, 9;     // and then the rows are stacked.
B << A, A, A;     // B is three horizontally stacked A's.
A.fill(10);       // Fill A with all 10's.

定义矩阵

// Eigen                                    // Matlab
MatrixXd::Identity(rows,cols)               // eye(rows,cols)
C.setIdentity(rows,cols)                    // C = eye(rows,cols)
MatrixXd::Zero(rows,cols)                   // zeros(rows,cols)
C.setZero(rows,cols)                        // C = zeros(rows,cols)
MatrixXd::Ones(rows,cols)                   // ones(rows,cols)
C.setOnes(rows,cols)                        // C = ones(rows,cols)
MatrixXd::Random(rows,cols)                 // rand(rows,cols)*2-1            // MatrixXd::Random returns uniform random numbers in (-1, 1).
C.setRandom(rows,cols)                      // C = rand(rows,cols)*2-1
VectorXd::LinSpaced(size,low,high)          // linspace(low,high,size)'
v.setLinSpaced(size,low,high)               // v = linspace(low,high,size)'
VectorXi::LinSpaced(((hi-low)/step)+1,      // low:step:hi
                    low,low+step*(size-1))  //

对矩阵的一些基础操作1

// Matrix slicing and blocks. All expressions listed here are read/write.
// Templated size versions are faster. Note that Matlab is 1-based (a size N
// vector is x(1)...x(N)).
// Eigen                           // Matlab
x.head(n)                          // x(1:n)
x.head<n>()                        // x(1:n)
x.tail(n)                          // x(end - n + 1: end)
x.tail<n>()                        // x(end - n + 1: end)
x.segment(i, n)                    // x(i+1 : i+n)
x.segment<n>(i)                    // x(i+1 : i+n)
P.block(i, j, rows, cols)          // P(i+1 : i+rows, j+1 : j+cols)
P.block<rows, cols>(i, j)          // P(i+1 : i+rows, j+1 : j+cols)
P.row(i)                           // P(i+1, :)
P.col(j)                           // P(:, j+1)
P.leftCols<cols>()                 // P(:, 1:cols)
P.leftCols(cols)                   // P(:, 1:cols)
P.middleCols<cols>(j)              // P(:, j+1:j+cols)
P.middleCols(j, cols)              // P(:, j+1:j+cols)
P.rightCols<cols>()                // P(:, end-cols+1:end)
P.rightCols(cols)                  // P(:, end-cols+1:end)
P.topRows<rows>()                  // P(1:rows, :)
P.topRows(rows)                    // P(1:rows, :)
P.middleRows<rows>(i)              // P(i+1:i+rows, :)
P.middleRows(i, rows)              // P(i+1:i+rows, :)
P.bottomRows<rows>()               // P(end-rows+1:end, :)
P.bottomRows(rows)                 // P(end-rows+1:end, :)
P.topLeftCorner(rows, cols)        // P(1:rows, 1:cols)
P.topRightCorner(rows, cols)       // P(1:rows, end-cols+1:end)
P.bottomLeftCorner(rows, cols)     // P(end-rows+1:end, 1:cols)
P.bottomRightCorner(rows, cols)    // P(end-rows+1:end, end-cols+1:end)
P.topLeftCorner<rows,cols>()       // P(1:rows, 1:cols)
P.topRightCorner<rows,cols>()      // P(1:rows, end-cols+1:end)
P.bottomLeftCorner<rows,cols>()    // P(end-rows+1:end, 1:cols)
P.bottomRightCorner<rows,cols>()   // P(end-rows+1:end, end-cols+1:end)

基础操作2

// Of particular note is Eigen's swap function which is highly optimized.
// Eigen                           // Matlab
R.row(i) = P.col(j);               // R(i, :) = P(:, j)
R.col(j1).swap(mat1.col(j2));      // R(:, [j1 j2]) = R(:, [j2, j1])
// Views, transpose, etc;
// Eigen                           // Matlab
R.adjoint()                        // R'
R.transpose()                      // R.' or conj(R')       // Read-write
R.diagonal()                       // diag(R)               // Read-write
x.asDiagonal()                     // diag(x)
R.transpose().colwise().reverse()  // rot90(R)              // Read-write
R.rowwise().reverse()              // fliplr(R)
R.colwise().reverse()              // flipud(R)
R.replicate(i,j)                   // repmat(P,i,j)

矩阵基础运算1

// All the same as Matlab, but matlab doesn't have *= style operators.
// Matrix-vector.  Matrix-matrix.   Matrix-scalar.
y  = M*x;          R  = P*Q;        R  = P*s;
a  = b*M;          R  = P - Q;      R  = s*P;
a *= M;            R  = P + Q;      R  = P/s;
                   R *= Q;          R  = s*P;
                   R += Q;          R *= s;
                   R -= Q;          R /= s;

矩阵基础运算2

// Vectorized operations on each element independently
// Eigen                       // Matlab
R = P.cwiseProduct(Q);         // R = P .* Q
R = P.array() * s.array();     // R = P .* s
R = P.cwiseQuotient(Q);        // R = P ./ Q
R = P.array() / Q.array();     // R = P ./ Q
R = P.array() + s.array();     // R = P + s
R = P.array() - s.array();     // R = P - s
R.array() += s;                // R = R + s
R.array() -= s;                // R = R - s
R.array() < Q.array();         // R < Q
R.array() <= Q.array();        // R <= Q
R.cwiseInverse();              // 1 ./ R
R.array().inverse();           // 1 ./ R
R.array().sin()                // sin(R)
R.array().cos()                // cos(R)
R.array().pow(s)               // R .^ s
R.array().square()             // R .^ 2
R.array().cube()               // R .^ 3
R.cwiseSqrt()                  // sqrt(R)
R.array().sqrt()               // sqrt(R)
R.array().exp()                // exp(R)
R.array().log()                // log(R)
R.cwiseMax(P)                  // max(R, P)
R.array().max(P.array())       // max(R, P)
R.cwiseMin(P)                  // min(R, P)
R.array().min(P.array())       // min(R, P)
R.cwiseAbs()                   // abs(R)
R.array().abs()                // abs(R)
R.cwiseAbs2()                  // abs(R.^2)
R.array().abs2()               // abs(R.^2)
(R.array() < s).select(P,Q );  // (R < s ? P : Q)
R = (Q.array()==0).select(P,R) // R(Q==0) = P(Q==0)
R = P.unaryExpr(ptr_fun(func)) // R = arrayfun(func, P)   // with: scalar func(const scalar &x);

求最小最大值、迹等

// Reductions.
int r, c;
// Eigen                  // Matlab
R.minCoeff()              // min(R(:))
R.maxCoeff()              // max(R(:))
s = R.minCoeff(&r, &c)    // [s, i] = min(R(:)); [r, c] = ind2sub(size(R), i);
s = R.maxCoeff(&r, &c)    // [s, i] = max(R(:)); [r, c] = ind2sub(size(R), i);
R.sum()                   // sum(R(:))
R.colwise().sum()         // sum(R)
R.rowwise().sum()         // sum(R, 2) or sum(R')'
R.prod()                  // prod(R(:))
R.colwise().prod()        // prod(R)
R.rowwise().prod()        // prod(R, 2) or prod(R')'
R.trace()                 // trace(R)
R.all()                   // all(R(:))
R.colwise().all()         // all(R)
R.rowwise().all()         // all(R, 2)
R.any()                   // any(R(:))
R.colwise().any()         // any(R)
R.rowwise().any()         // any(R, 2)

点乘等

// Dot products, norms, etc.
// Eigen                  // Matlab
x.norm()                  // norm(x).    Note that norm(R) doesn't work in Eigen.
x.squaredNorm()           // dot(x, x)   Note the equivalence is not true for complex
x.dot(y)                  // dot(x, y)
x.cross(y)                // cross(x, y) Requires #include <Eigen/Geometry>

特征值与特征向量

// Eigenvalue problems
// Eigen                          // Matlab
A.eigenvalues();                  // eig(A);
EigenSolver<Matrix3d> eig(A);     // [vec val] = eig(A)
eig.eigenvalues();                // diag(val)
eig.eigenvectors();               // vec
// For self-adjoint matrices use SelfAdjointEigenSolver<>

形式转换

 Type conversion
// Eigen                  // Matlab
A.cast<double>();         // double(A)
A.cast<float>();          // single(A)
A.cast<int>();            // int32(A)
A.real();                 // real(A)
A.imag();                 // imag(A)
// if the original type equals destination type, no work is done

矩阵初始化0

// Note that for most operations Eigen requires all operands to have the same type:
MatrixXf F = MatrixXf::Zero(3,3);
A += F;                // illegal in Eigen. In Matlab A = A+F is allowed
A += F.cast<double>(); // F converted to double and then added (generally, conversion happens on-the-fly)

Map等操作

// Eigen can map existing memory into Eigen matrices.
float array[3];
Vector3f::Map(array).fill(10);            // create a temporary Map over array and sets entries to 10
int data[4] = {1, 2, 3, 4};
Matrix2i mat2x2(data);                    // copies data into mat2x2
Matrix2i::Map(data) = 2*mat2x2;           // overwrite elements of data with 2*mat2x2
MatrixXi::Map(data, 2, 2) += mat2x2;      // adds mat2x2 to elements of data (alternative syntax if size is not know at compile time)

求解Ax = b

// Solve Ax = b. Result stored in x. Matlab: x = A \ b.
x = A.ldlt().solve(b));  // A sym. p.s.d.    #include <Eigen/Cholesky>
x = A.llt() .solve(b));  // A sym. p.d.      #include <Eigen/Cholesky>
x = A.lu()  .solve(b));  // Stable and fast. #include <Eigen/LU>
x = A.qr()  .solve(b));  // No pivoting.     #include <Eigen/QR>
x = A.svd() .solve(b));  // Stable, slowest. #include <Eigen/SVD>
// .ldlt() -> .matrixL() and .matrixD()
// .llt()  -> .matrixL()
// .lu()   -> .matrixL() and .matrixU()
// .qr()   -> .matrixQ() and .matrixR()
// .svd()  -> .matrixU(), .singularValues(), and .matrixV()

以上就是R语言学习RcppEigen进行矩阵运算的详细内容,更多关于RcppEigen矩阵运算的资料请关注我们其它相关文章!

(0)

相关推荐

  • R语言基本运算的示例代码

    1.基本运算 1.1 加.减.乘.除 + - * / 在赋值中可以使用=,也可以使用<-. 1.2余数.整除 %% %/% 1.3 取绝对值 abs() 判断正负号sign() 1.4幂指数 ^ 平方根sqart () 1.5 以二为底的对数:log2() 以十为底的对数:log10() 自定义底的对数:log(c,base=) 自然常数e的对数:log(a,base=exp(1)) 2.向量运算 向量是有相同基本类型的元素序列,一维数组,定义向量的最常用办法是使用函数c(),它把若干个数值或字

  • R语言RcppEigen计算点乘与矩阵乘法连乘算法错误解决

    计算点乘与矩阵乘法连乘计算错误 当我们想将 R 中的连乘(如下公式所示)修改成 Rcpp 代码时, t(X)^2 %*% X 理论上我们只用在 .cpp 代码中输入下述语句即可(默认使用了 RcppEigen 库): X.adjoint().array().square() * X.array().square(); 但实际上这样会会出现问题,原因是 X.adjoint().array().square() 与 X.array().square() 没有成功转化成 Eigen::MatrixXd

  • R语言中向量和矩阵简单运算的实现

    一.向量运算 向量是有相同基本类型的元素序列,一维数组,定义向量的最常用办法是使用函数c(),它把若干个数值或字符串组合为一个向量. 1.R语言向量的产生方法 > x <- c(1,2,3) > x [1] 1 2 3 2.向量加减乘除都是对其对应元素进行的,例如下面 > x <- c(1,2,3) > y <- x*2 > y [1] 2 4 6 (注:向量的整数除法是%/%,取余是%%.) 3.向量的内积,有两种方法. 第一种方法:%*% > x

  • R语言创建矩阵的实现方法

    矩阵 向量vector用于描述一维数据,是R语言中最基础的数据结构形式 矩阵matrix可以描述二维数据,和向量相似,其内部元素可以是实数.复数.字符.逻辑型数据 矩阵包含行和列,分为单位矩阵.对角矩阵和普通矩阵.矩阵可以进行四则运算,以及进行求特征值.特征向量等运算 矩阵matrix使用两个下标来访问元素,A[i,j]表示矩阵A第i行.第j列的元素 矩阵创建--matrix函数 matrix函数创建矩阵,其格式为: matrix(data = NA,nrow = 1,ncol = 1,byro

  • R语言 实现矩阵相乘100次

    [D1 D2]2*1 [T1 T2]1*2 要求D1和D2随机的变动, 矩阵相乘100次 rm(list=ls()) gc() options(scipen = 2000) ##################写成函数###########3 #################定义TT矩阵(1*2) TT <- matrix(c(1,3),1,2) DD<- matrix(c(1,2),2,1) result1 <- DD %*% TT m1=result1 ##############

  • R语言学习RcppEigen进行矩阵运算

    目录 创建cpp文件 代码示例 其他矩阵操作 命名 基础用法 定义矩阵 对矩阵的一些基础操作1 基础操作2 矩阵基础运算1 矩阵基础运算2 求最小最大值.迹等 点乘等 特征值与特征向量 形式转换 矩阵初始化0 Map等操作 求解Ax = b 前面我们介绍了一些基本的Rcpp的用法:让你的R代码更快--Rcpp入门,但用基础的Rcpp来进行矩阵运算还是非常麻烦,没有现成的函数来让我们使用. 这时我们就想到:是否可以调用别的库来解决矩阵运算的一些问题呢?这就需要我们的RcppEigen包,也就是C+

  • R语言学习Rcpp基础知识全面整理

    目录 1. 相关配置和说明 2. 常用数据类型 3. 常用数据类型的建立 4. 常用数据类型元素访问 5. 成员函数 6. 语法糖 6.1 算术和逻辑运算符 6.2. 常用函数 7. STL 7.1. 迭代器 7.2. 算法 7.3. 数据结构 7.3.1. Vectors 7.3.2. Sets 7.3.3. Maps 8. 与R环境的互动 9. 用Rcpp创建R包 10. 输入和输出示例 如何传递数组 通过.attr("dim")设置维数 函数返回一维STL vector 函数返回

  • R语言学习笔记之lm函数详解

    在使用lm函数做一元线性回归时,发现lm(y~x+1)和lm(y~x)的结果是一致的,一直没找到两者之间的区别,经过大神们的讨论和测试,才发现其中的差别,测试如下: ------------------------------------------------------------- ------------------------------------------------------------- 结果可以发现,两者的结果是一样的,并无区别,但是若改为lm(y~x-1)就能看出+1和

  • R语言学习代码格式一键美化

    目录 RStudio 快捷操作 formatR 包 配合 Shiny 包使用 参考 当写R代码时,很多时候写的代码或者看到的代码缩进都很难统一到标准的格式.这时为了规范化代码,我们需要再代码中一行一行查代码,将其修改成标准的格式. 那么我们有没有一键代码整理的方式或者R包呢? 答案是有的! 下面我们介绍两种方法. RStudio 快捷操作 如果你使用的是RStudio 写代码的话,那么只用全选代码(Ctrl + A),而后输入如下命令: Ctrl + Shift + A 即可简单调整缩进与格式.

  • R语言学习ggplot2绘制统计图形包全面详解

    目录 一.序 二.ggplot2是什么? 三.ggplot2能画出什么样的图? 四.组装机器 五.设计图纸 六.机器的零件 1. 零件--散点图 1) 变换颜色 2) 拟合曲线 3) 变换大小 4) 修改透明度 5) 分层 6) 改中文 2. 零件--直方图与条形图 1) 直方图 2) 润色 3) 条形图 3. 零件--饼图 4. 零件--箱线图 5. 零件--小提琴图 6. 零件打磨 7. 超级变变变 8. 其他常用零件 七.实践出真知 八.学习资源 九.参考资料 一.序 作为一枚统计专业的学

  • R语言学习初识Rcpp类型List

    目录 当我们想将 Rcpp 中的多种类型的对象通过一个 return 函数返回时,此时就需要将我们的所有对象整理成一个 Rcpp::List 型,然后再进行返回. 但相比于 R 中的 list(mat1 = mat1, mat2 = mat2) ,Rcpp 中的列表创建就相对复杂一些,需要使用 create() 函数,如下面例子所示: Rcpp::List ListFun(MatrixXd X) { Eigen::MatrixXd mat1, mat2; return List::create(

  • R语言学习笔记缺失数据的Bootstrap与Jackknife方法

    目录 一.题目 二.解答 a)Bootstrap与Jackknife进行估计 b)均值与变异系数(大样本)的标准差解析式推导与计算 c)缺失插补前的Bootstrap与Jackknife d)比较各种方式的90%置信区间情况(重复100次实验) 填补之前进行Bootstrap或Jackknife 填补之后进行Bootstrap或Jackknife 一.题目 下面再加入缺失的情况来继续深入探讨,同样还是如习题1.6的构造方式来加入缺失值,其中a=2, b = 0 我们将进行如下几种操作: 二.解答

  • R语言学习之线图的绘制详解

    目录 线图 单线图 多线图 横轴文本线图 线图 线图是反映趋势变化的一种方式,其输入数据一般也是一个矩阵. 单线图 假设有这么一个矩阵,第一列为转录起始位点及其上下游5 kb的区域,第二列为H3K27ac修饰在这些区域的丰度,想绘制一张线图展示. profile="Pos;H3K27ac -5000;8.7 -4000;8.4 -3000;8.3 -2000;7.2 -1000;3.6 0;3.6 1000;7.1 2000;8.2 3000;8.4 4000;8.5 5000;8.5"

  • R语言学习VennDiagram包绘制韦恩图示例

    目录 引言 一 需要安装和导入的包 二 使用函数及参数 三 知道各个数据集的个数以及重叠(交叉)的个数 2.1 两个已知数据集的韦恩图 2.2 三个已知数据集的韦恩图 四 根据数据集合绘制韦恩图 4.1 四个数据集合 4.2 五个数据集合 引言 本版块会持续分享一些常用的结果展示的图形. 在得到数据之后,我们经常会用到维恩图来展示各个数据集之间的重叠关系.本文简单的介绍R语言中的VennDiagram包绘制数据集的维恩图. 一 需要安装和导入的包 install.packages("VennDi

  • R语言入门使用RStudio制作包含Rcpp代码的R包

    目录 1. 创建项目 2. 修改一些文件 3. 打包 4. 使用Eigen或其它依赖库会出现的问题 前面博客中有提及,当我们进行模拟想要再次进行提速时,通常都会使用Rcpp将我们的R代码改成C++代码.具体Rcpp的使用可参考博客:Rcpp入门R代码提速方法过程,R语言学习RcppEigen进行矩阵运算. 平时在我们使用的时候,直接使用Rcpp::sourceCpp()就可以直接将我们的C++代码中的函数进行导入,这不会遇到什么问题,但如果我们想要使用snowfall进行并行时就不能再这样做了.

随机推荐