[R] Matrix multiplication - code problem
Ben Bolker
bolker at ufl.edu
Thu Apr 2 03:55:41 CEST 2009
I think your problem is with R's behavior of dropping array indices
when dim==1.
Simulating that
> m1 <- matrix(1:2,nrow=2)
> m2 <- matrix(1:2,ncol=2)
> m1 %*% m2
[,1] [,2]
[1,] 1 2
[2,] 2 4
> m1[,] %*% m2[,]
[,1]
[1,] 5
[1,] 5
> m1[,,drop=FALSE] %*% m2[,,drop=FALSE]
[,1] [,2]
[1,] 1 2
[2,] 2 4
However, if you use [,,i,drop=FALSE] in your context,
you will also fail to drop the third array dimension, which
you *do* want to drop (i.e. you will end up with an
array of dimensions [2,1,1] rather than a matrix of
dimensions [2,1] as you would like.
MarcioRibeiro wrote:
>
> Hi again...
> I will get an array with 5 matrix 2x2, with dimension 2x2x5
> This code below works fine... And I am applying the same procedure...
> The problem might be when I do the permutation of the array, but I checked
> the dimension and its all right...
>
> array1 <- array(1:30,dim=c(3,2,5))
> array2 <- array(1:20,dim=c(2,2,5))
> result <- array(dim=c(dim(array1)[1], dim(array2)[2], dim(array1)[3]))
> for (i in 1: dim(array1)[3]){
> result[,,i] <- array1[,,i]%*%array2[,,i]
> }
>
> Thanks...
>
>
> Ben Bolker wrote:
>>
>>
>>
>> MarcioRibeiro wrote:
>>>
>>> Hi listers,
>>> I am having some trouble in a matrix multiplication...
>>> I have already checked some posts, but I didn't find my problem...
>>> I have the following code...
>>> But I am not getting the right multiplication...
>>> I checked the dimension and they are fine...
>>>
>>> id_y <- array(1:10,dim=c(2,1,5))
>>> id_yt<-aperm(id_y,c(2,1,3))
>>> m_id<-array(dim=c(dim(id_y)[1],dim(id_y)[1],dim(id_y)[3]))
>>> for (i in 1:dim(id_y)[3]){
>>> m_id[,,i]<-id_y[,,i]%*%id_yt[,,i]
>>> }
>>> m_id
>>>
>>>
>>
>> What did you expect to happen?
>>
>> Ben Bolker
>>
>>
>
>
--
View this message in context: http://www.nabble.com/Matrix-multiplication---code-problem-tp22835003p22838040.html
Sent from the R help mailing list archive at Nabble.com.
More information about the R-help
mailing list