nilsinelabore
nilsinelabore

Reputation: 5135

Error in Matrix %*% Matrix: requires numeric/complex matrix/vector arguments

I am trying to do matrix multiplication in R. I have successfully created and run the matrix Matrix1, but caught an error when trying to do the multiplication:

Matrix1 = new("markovchain", states = c("state 1", "state 2", "state 3"),
              transitionMatrix = matrix(data = c(0,1,0,
                                                0.7,0,0.3,
                                                0.5, 0, 0.5),
                                        byrow = TRUE, nrow = 3), 
               name = "Matrix Name")

Matrix1

TwoStep = Matrix1%*%Matrix1
TwoStep

I found out that Matrix1 is in S4 type. I tried to use as.matrix to convert it from S4 into vector but it did not work:

> as.matrix(Matrix1)
Error in as.vector(data) : 
  no method for coercing this S4 class to a vector

Upvotes: 3

Views: 78

Answers (2)

nilsinelabore
nilsinelabore

Reputation: 5135

Alternatively, using power operator, ^, directly to a markovchain object to calculate powers of its transition matrix:

Matrix1 ^ 2

output:

> Matrix1^2
Matrix Name^2 
 A  3 - dimensional discrete Markov Chain defined by the following states: 
 state 1, state 2, state 3 
 The transition matrix  (by rows)  is defined as follows: 
        state 1 state 2 state 3
state 1    0.70     0.0    0.30
state 2    0.15     0.7    0.15
state 3    0.25     0.5    0.25

Upvotes: 1

M--
M--

Reputation: 29153

library(markovchain)

Matrix1 = new("markovchain", states = c("state 1", "state 2", "state 3"),
              transitionMatrix = matrix(data = c(0,1,0,
                                                 0.7,0,0.3,
                                                 0.5, 0, 0.5),
                                         byrow = TRUE, nrow = 3), 
              name = "Matrix Name")

class(Matrix1)
#> [1] "markovchain"
#> attr(,"package")
#> [1] "markovchain"
class(Matrix1[])
#> [1] "matrix" "array"


Matrix1[]%*%Matrix1[]
#>         state 1 state 2 state 3
#> state 1    0.70     0.0    0.30
#> state 2    0.15     0.7    0.15
#> state 3    0.25     0.5    0.25

Created on 2024-04-09 with reprex v2.0.2

Upvotes: 4

Related Questions