user4275591
user4275591

Reputation:

Scalar Multiplication in R

I'm trying to perform simple scalar multiplication in R, but I'm running into a bit of an issue.

In linear algebra I would do the following:

scalar multiplication

Here's how I've implemented this in R:

A <- matrix(1:4, 2, byrow = TRUE)
c <- matrix(rep(3, 4), 2)
A * c

This produces the correct output, but creating the scalar matrix c will be cumbersome when it comes to larger matrices.

Is there a better way to do this?

Upvotes: 3

Views: 36181

Answers (3)

aniket tare
aniket tare

Reputation: 1

A=c(1,2,3,4) A m=matrix(A,nrow=2,ncol=2) m c=3 m*c

Upvotes: 0

crogg01
crogg01

Reputation: 2526

In R the default is scalar. For matrix multiplication use %*%. t is transpose and solve will give you the inverse. Here are some examples:

a = matrix(1:4,2,2)
3 * a
c(1:2) %*% a
c(1:2) %*% t(a)
solve(a)

Here is a link: matrix algebra in R

Upvotes: 12

Andrew G
Andrew G

Reputation: 103

Use the function drop() to convert a 1x1 variable matrix into a "real" scalar. So you can write drop(c)*A and you don't need to replace c with the value itself.

Upvotes: 7

Related Questions