Emil Krabbe
Emil Krabbe

Reputation: 101

How to do the matrix product of two matrices in R and C++ respectively

I have a question on why matrix multiplication is %*% in R but just * in C++.

Example:

in R script:

FunR <- function(mX, mY) {
  mZ = mX %*% mY
  mZInv = solve(mZ)
  return(mZInv)
}

in C++ script:

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

  // [[Rcpp::export]]
  mat FunC(mat mX, mat mY) { 
    mat mZ = mX * mY;
    mat mZInv = mZ.i();
   return mZInv; 
  }

I ask because C++ can be easily incorporated into R documents.

Also, the "*" character is used to multiply matrices in R but it is not the standard matrix product as we know it. How are you supposed to know this stuff?

Upvotes: 0

Views: 170

Answers (1)

JaMiT
JaMiT

Reputation: 16853

R and C++ are different languages. There is no reason to expect them to share syntax. You should be more surprised when the syntax matches than when it differs.

That being said, when you have a package, like Rcpp, that integrates languages, there usually is some attempt to make the syntax consistent. So why not use the same operator as R in this case? Because it is not possible. The list of operators in C++ is fixed, and %*% is not on that list. The operator * is on the list, though, so that operator could be chosen. Always better to choose something that can be chosen than to have nothing work. :)

(In case it got missed along the way: C++ has no native support for matrix operations. There is no matrix multiplication "in C++", only in specific libraries, such as Armadillo.)

Upvotes: 1

Related Questions