Matlab bsxfun(@times,...,...) equivalent in R -
has r got equivalent of matlab bsxfun(@times,a,b)
? suppose 1 perform element wise multiplication
on matrix a,b
:
matlab:
a=[1 0 3 -4]; b=[0 1 5 7; 2 9 -3 4]; bsxfun(@times,a,b) = [0 0 15 -28; 2 0 -9 -16]
r:
a<-c(1,0,3,-4) b<-matrix(c(0,2,1,9,5,-3,7,4),nrow = 2,ncol = 4) * b = matrix(c(0,0,3,-36,5,0,21,-16),nrow = 2,ncol = 4)
any idea on way r gets results of above of a*b
, expecting identical matlab bsxfun(@times,a,b)
edit:
bsxfun("*",repmat(a,2,1),b) # using r {pracma}
best
do column major matrices, since r-convention:
> b<-matrix(c(0,2,1,9,5,-3,7,4),nrow = 4,ncol = 2) > a*b [,1] [,2] [1,] 0 5 [2,] 0 0 [3,] 3 21 [4,] -36 -16
if take original construction of b
bit of unpleasant surprise when try use sweep
:
> b2<-matrix(c(0,2,1,9,5,-3,7,4),nrow = 2,ncol = 4) > sweep(b2, 2, a, '*') [,1] [,2] [,3] [,4] [1,] 0 0 15 -28 [2,] 2 0 -9 -16
since matrix
function uses column major filling of postions, , didn't specify byrow=true in call, b
-matrix different matlab matrix.
> b3<-matrix(c(0,2,1,9,5,-3,7,4),nrow = 2,ncol = 4, byrow=true) > sweep(b3, 2, a, '*') [,1] [,2] [,3] [,4] [1,] 0 0 3 -36 [2,] 5 0 21 -16
Comments
Post a Comment