0

I have 2 matrices. A, B A has 100 rows and 350 columns B has 1 rows and 350 columns(in the exact same order as they are in A)

I want the third data frame matrix C which will have 100 rows and 350 columns Value in any cell in C will be x * A + (1-x) * B for the same corresponding column values in A and B respectively.

I can correctly do this by applying various/multiple loops but it is taking a lot of time.

Is there any direct method to apply this formula in one go on all the 350 columns (as the order/index of all the columns in all the matrices A, B, C are same)

josliber
  • 43,891
  • 12
  • 98
  • 133
  • What's `x` in your formula? – Thomas Feb 26 '14 at 07:47
  • Does B have 1 row or 100 rows? – josliber Feb 26 '14 at 07:52
  • 1
    If `A` and `B` have the same number of rows/columns and `x` is a scalar, then `function(A, B, x) {A*x + B*(1-x)}` will do the job. – tonytonov Feb 26 '14 at 07:56
  • 2
    Welcome to SO! Please post a _minimal_ example of both input and desired output. Just enough rows/cols to illustrate your point, not more, not less. See [**here**](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610#5963610) and [**here**](http://sscce.org/). – Henrik Feb 26 '14 at 07:57
  • There is a bug in the question. The formula seems to be the usual linear interpolation x A + (1-x) B, x from [0, 1] between A and B, where A and B should have same dimensions. – mvw Feb 26 '14 at 08:03

2 Answers2

2

Assuming x is a constant, all you should need is:

t(apply(x*A, 1, `+`, B*(1-x)))
Thomas
  • 43,637
  • 12
  • 109
  • 140
0
A<-matrix(runif(35000),nrow=100)
B<-matrix(1:350,nrow=1)

x<-2                                       # or whatever

B.M<-matrix(rep(B,100),nrow=100,byrow=T)   # expand B out to same size

(x * A) + ((1-x) * B.M)
Troy
  • 8,581
  • 29
  • 32