0

I know it is possible to use R for matrix algebra, but I am wondering whether it is possible to use it for this purpose without having specified the elements of the vectors and matrices as numbers but as "strings" or variables. So maybe an example may help to express my concern:

What I know that R can do it is this:

https://latex.codecogs.com/gif.latex?\begin{pmatrix}&space;1&space;&&space;2&space;\\&space;1&space;&&space;2&space;\end{pmatrix}&space;*&space;\begin{pmatrix}&space;3&space;\\&space;4&space;\end{pmatrix}&space;=&space;\begin{pmatrix}&space;11&space;\\&space;11&space;\end{pmatrix}

What I want to know is whether the following is possible in R:

https://latex.codecogs.com/gif.latex?\begin{pmatrix}&space;a_{11}&space;&&space;a_{12}&space;\\&space;a_{21}&space;&&space;a_{22}&space;\end{pmatrix}&space;*&space;\begin{pmatrix}&space;b_{1}&space;\\&space;b_{2}&space;\end{pmatrix}&space;=&space;\begin{pmatrix}&space;a_{11}*b_{1}+a_{12}*b_{2}&space;\\&space;a_{21}*b_{1}+a_{22}*b_{2}&space;\end{pmatrix}

Is it possible to do this in R or is there any other programming language which does it?

Benny
  • 1
  • Do you mean you want to do symbolic matrix computations? If so, take a look at `Ryacas` package. [This link](https://stackoverflow.com/questions/21858668/symbolic-matrix-multiplication-by-ryacas) may help as well. – user2474226 Jul 24 '20 at 06:45

1 Answers1

0

Suppose we have the following two character matrices:

a <- matrix(c("a11", "a12", "a21", "a22"), nrow = 2)
b <- matrix(c("b1", "b2"), nrow = 2)

a
#>      [,1]  [,2] 
#> [1,] "a11" "a21"
#> [2,] "a12" "a22"
b
#>      [,1]
#> [1,] "b1"
#> [2,] "b2"

We can get your desired outcome using apply

matrix(apply(a, 2, paste, b, sep = " * ", collapse = " + "), ncol = ncol(b))
#>      [,1]                 
#> [1,] "a11 * b1 + a12 * b2"
#> [2,] "a21 * b1 + a22 * b2"

This should be applicable to larger matrices too:

a <- matrix(c("a11", "a21", "a31", 
              "a12", "a22", "a32",
              "a13", "a23", "a33"), byrow = TRUE, nrow = 3)

b <- matrix(c("b1", 
              "b2", 
              "b3"), byrow = TRUE, nrow = 3)


matrix(apply(a, 2, paste, b, sep = " * ", collapse = " + "), ncol = 1)
#>      [,1]                            
#> [1,] "a11 * b1 + a12 * b2 + a13 * b3"
#> [2,] "a21 * b1 + a22 * b2 + a23 * b3"
#> [3,] "a31 * b1 + a32 * b2 + a33 * b3"

Created on 2020-07-24 by the reprex package (v0.3.0)

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87