JeongHyun
JeongHyun

Reputation: 1

using solve function to solve an equation in R

I'm JeongHyun.

I think this is related to basic R logic, but anyway, I'm confused how 'mat' and 'b' is solved because 'mat' is 3 by 3 matrix and 'b' is 1 by 3 matrix. As far as I know, ncol of former matrix and nrow of latter matrix should be same but in this case they are not same.

x=c(1,3,5,2,5,1,2,3,8)
x
#[1] 1 3 5 2 5 1 2 3 8

mat=matrix(x,nrow=3,ncol=3,byrow=T)
mat

     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    5    1
[3,]    2    3    8

b=c(10,8,3)
b
#[1] 10  8  3

solve(mat,b)
[1] -9.28  5.16  0.76

Please let me know how it works.

Thank you.

Upvotes: 0

Views: 1073

Answers (1)

Ishan Juneja
Ishan Juneja

Reputation: 421

R will consider a vector as column matrix in such situations. Proof:

x=c(1,3,5,2,5,1,2,3,8)
x
#[1] 1 3 5 2 5 1 2 3 8

mat=matrix(x,nrow=3,ncol=3,byrow=T)
mat

     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    5    1
[3,]    2    3    8

b=c(10,8,3)
b
#[1] 10  8  3

b<-as.matrix(b)

solve(mat,b)
      [,1]
[1,] -9.28
[2,]  5.16
[3,]  0.76

b1<-t(b)

solve(mat,b1)
#Error in solve.default(mat, b1) : 
  'b1' (1 x 3) must be compatible with 'a' (3 x 3)

Upvotes: 1

Related Questions