# Re: [S] Loop avoiding

Franz-Josef Mueter (mueter@ims.uaf.edu)
Wed, 29 Jul 1998 11:38:52 -0800 (AKDT)

> max(apply(A*t(B),1,sum))

or better yet (much faster than apply):

> max(row.sum(A*t(B)))

where:

> row.sum
function(M)
{
nc <- ncol(M)
c(M %*% array(1, c(nc, 1)))
}

The latter resulted in the following times on
Version 3.3 Release 1 for Sun SPARC, SunOS 4.1.x
for 500*10 and 10*500 matrices (about a 20-25 fold improvement
using row.sum):

> unix.time(max(diag(A%*%B)))
[1] 1.833334 0.416667 3.000000 0.000000 0.000000

> unix.time(max(apply(A*t(B),1,sum)))
[1] 0.28333282 0.05000019 1.00000000 0.00000000 0.00000000

> unix.time(max(row.sum(A*t(B))))
[1] 0.08333397 0.01666689 0.00000000 0.00000000 0.00000000

Hope this helps

Franz

***************************************************************

Since all models are wrong, the scientist must be alert
to what is importantly wrong. It is inappropriate to be
- Box, 1976

***************************************************************
Franz-Josef Mueter | Voice: (907) 474-7839
Institute of Marine Sciences | (907) 479-8815
School of Fisheries and Ocean Sciences | Fax: (907) 474-1943
---------------------------------------------------------------

On Wed, 29 Jul 1998, Marcel Wolbers wrote:

> Dear S-users
>
> I have a n*m matrix A and a m*n matrix B where n is large (say 10000).
> The measure I'm interested in is
> > max(diag(A%*%B))
> However the calculation above takes too long, has to calculate many things
> I don't need (the off-diagonal elements) and uses too much memory for
> n large.
>
> Of course I could avoid the matrix multiplication by using a for-loop, i.e.
> > x <- vector("numeric",10000)
> > for (index in 1:10000)
> > { x[index] <- A[index,]%*%B[,index] }
> > max(x)
>
> But there must be a more efficient way to do it...
> It should be easy but I just can't find it.
>
> Thanks a lot for your help.
>
> Marcel Wolbers
> -----------------------------------------------------------------------
> This message was distributed by s-news@wubios.wustl.edu. To unsubscribe
> send e-mail to s-news-request@wubios.wustl.edu with the BODY of the
> message: unsubscribe s-news
>
-----------------------------------------------------------------------
This message was distributed by s-news@wubios.wustl.edu. To unsubscribe
send e-mail to s-news-request@wubios.wustl.edu with the BODY of the
message: unsubscribe s-news