Edward Armstrong
Edward Armstrong

Reputation: 349

Dividing an array by a single value and multiplying by matrix

This is a two part question. I have an array of sea level pressure data [36,21,12012] representing longitude, latitude and monthly time slices. Firstly I need to divide all of the numbers in the array by one value. I then need to multiply each of the resulting time slices by a matrix of the same dimension [36,21].

How do I do this? Thanks in advance!

Upvotes: 0

Views: 1160

Answers (2)

Kyle.
Kyle.

Reputation: 156

In R, you should be able to divide everything by a single value at once. For example, if your matrix is X, and the value is v, you can do newMat <- X/v. Matrix multiplication is similar. If the matrix you want to multiply your previous answer is multMat, you can get your final result with
result <- newMat %*% multMat.

In short:

result <- X/v %*% multMat

Upvotes: 1

Iancovici
Iancovici

Reputation: 5731

You're refering to vector multiplication as oppose to matrix multiplication.

You should be able to do

Assign value

a = c(36, 21, 12012)

Vector Arithmetic, for single element division

a = a/value

Matrix Multiplication with %*% operator

Not sure what are the matrices you're multiplying, but number of rows of first one should be the same as number of columns of the second one.

Here's an example code I just did

x <- matrix(1:9,nrow=3)
print("X is:")
print(x)
y <- c(1,2,3)
y = y*2
print("Y is")
print(y)
print(x %*% y/2)

Results:

[1] "X is:"

      [,1] [,2] [,3]

[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9
[1] "Y is"
[1] 2 4 6
     [,1]
[1,]   30
[2,]   36
[3,]   42

Upvotes: 0

Related Questions