s-news
[Top] [All Lists]

Re: Matrix minus A Vector

To: "Chen,Sichong" <sichong.chen@postgrad.manchester.ac.uk>
Subject: Re: Matrix minus A Vector
From: Tim Hesterberg <timh@insightful.com>
Date: 26 Oct 2006 15:05:37 -0700
Cc: <s-news@lists.biostat.wustl.edu>
In-reply-to: <20061026200404.339B413731F@mailgate.biostat.wustl.edu> (sichong.chen@postgrad.manchester.ac.uk)
References: <20061026200404.339B413731F@mailgate.biostat.wustl.edu>
A similar question came up on R-help (/ rather than -), and the number
of different proposals was amazing:

x/matrix(v, nrow(x), ncol(x), byrow = TRUE))
sweep(x, 2, v, "/")
x / rep(v, each = nrow(x))
x / outer(rep(1, nrow(x)), v)
x %*% diag(1/v)
t(apply(x, 1, function(x) x/v))
x/rep(v, each=nrow(x))
t(apply(x, 1, "/", v))
library(reshape); iapply(x, 1, "/", v)  # R only
t(t(x)/v)
scale(x, center = FALSE, v)  # not previously suggested

Some of these are terribly inefficient.  The best is generally
        x / rep(v, each = nrow(x))

Even that is slower than need be -- you really shouldn't need to
replicate v.  On my to-do list is to create colMinus, colTimes,
colDivide, colPlus, so you could do e.g.
        colMinus(x, colMeans(x))
and have the calculations be done in C.

Tim Hesterberg


>Dear Users
>
>I have a matrix (4x3)
>4      5       6       
>2      4       5       
>2      4       6       
>6      5       5       
>3      8       9       
>
>And a vector   (1x3)
>2      4       3       
>
>I would like to use the first column of the matrix minus the first number of
>the vector "2", then the second column of the matrix minus the second number
>of the vector "4" and so on.
>
>The final result of a matrix is supposed to be:
>2      1       3       
>0      0       2       
>0      0       3       
>4      1       2       
>1      4       6       
>
>I know the stupid way is to calculate one column by one column, but I think
>there must be some quicker and smarter way to do it.
>
>Many thanks,
>Regards,
>Sichong
>SPlus 7.0 & FinMetrics 2.0 User
>Windows XP
>
>
>
>--------------------------------------------------------------------
>This message was distributed by s-news@lists.biostat.wustl.edu.  To
>unsubscribe send e-mail to s-news-request@lists.biostat.wustl.edu with
>the BODY of the message:  unsubscribe s-news


<Prev in Thread] Current Thread [Next in Thread>