[R] efficiently multiply different matrices in 3-d array with different vectors?
Suzen, Mehmet
msuzen at gmail.com
Sun Dec 30 20:08:04 CET 2012
On 29 December 2012 20:35, arun <smartpink111 at yahoo.com> wrote:
>> Is it possible to obtain the same result as X without converting X to R?
What do you mean by the same result? There is a relationship between X and R.
If you express this relationship algebraically, you can get X directly using
Y and Z tensors, vice versa.
Too many terms in the example you have given. So I would demonstrate
the possibility
with a smaller example. Think of X as intermediate results from Matrix
multiplication.
You need to use Riemann notation instead of Einstein's [*]. However
you may end up computing more terms then you need.
It makes sense to use tensorA only if you know algebraic relationships
well. If you think
in terms of components and positioning intermediate results as most R
programmers do
i,e. using cbind, moving that column here in there etc,, probably
tensorA is not suited
for you.
Hope it answers your question.
[*]
library(tensorA)
# intermediate results via component wise multiplication
set.seed(42)
A <-matrix(rnorm(10), 5, 2)
set.seed(43)
x <-matrix(rnorm(2), 2, 1)
b <- A %*% x
bInter <- do.call(cbind,lapply(seq_len(dim(A)[1]),function(i) A[i,]*x))
# intermediate results via tensor multiplication
set.seed(42)
At <-to.tensor(rnorm(10), c(a=5, b=2))
set.seed(43)
xt <-to.tensor(rnorm(2), c(c=2))
bt <- At%r%xt # Riemann sum
bInterT <- t(cbind(bt[,,1][,1],bt[,,2][,2]))
# Multiplication from intermediate results
binterM <- t(do.call(cbind, lapply(1:5, function(i) sum(bInter[,i]))))
binterTM <- t(do.call(cbind, lapply(1:5, function(i) sum(bInterT[,i]))))
# Correctness
# Correctness
bInterT
# [,1] [,2] [,3] [,4] [,5]
#[1,] -0.05142981 0.02118395 -0.01362231 -0.02374106 -0.01516563
#[2,] 0.16710413 -2.38004921 0.14905054 -3.17821889 0.09874990
bInter
# [,1] [,2] [,3] [,4] [,5]
#[1,] -0.05142981 0.02118395 -0.01362231 -0.02374106 -0.01516563
#[2,] 0.16710413 -2.38004921 0.14905054 -3.17821889 0.09874990
b
# [,1]
#[1,] 0.11567432
#[2,] -2.35886526
#[3,] 0.13542823
#[4,] -3.20195995
#[5,] 0.08358427
binterM
# [,1]
#[1,] 0.11567432
#[2,] -2.35886526
#[3,] 0.13542823
#[4,] -3.20195995
#[5,] 0.08358427
binterTM
# [,1]
#[1,] 0.11567432
#[2,] -2.35886526
#[3,] 0.13542823
#[4,] -3.20195995
#[5,] 0.08358427
More information about the R-help
mailing list