# [R] matrix dimension and for loop

Uwe Ligges ligges at statistik.uni-dortmund.de
Wed Apr 10 16:47:48 CEST 2002

```ggrothendieck at yifan.net wrote:
>
> > My questions are that if I have
> >
> > > x<-rnorm(50)
> > > dim(x)<-c(10,5)
> > > y=1:5
> > > Z<-matrix(0,NROW(x),NROW(y))
> > > for (j in 1:NROW(y)) Z[,j]<-x[,j]*y[j]
> >
> > 1. Is there any other way to write this without 'for'
> > loop?
> >
> > 2. and if I don't know the dimension of x, which could
> > be only 1 column, how could I write the command
>
> I thought I would collect together some of the solutions that have
> been posted as well as mention a few others.  I have also added
> some discussion particularly with reference to the second question.
> There appears to be a myriad of ways to address this problem in R.
> Since I am learning R I found it useful for myself to explore various
> solutions and maybe others will find this helpful too.
>
> The problem is to multiply the jth column of a matrix x by y[j] for each j.
> Its also possible for x to be a vector in which case y may be a scalar.
>
> The first 4 solutions regard x as a one column matrix if x is a vector and
> so always return a matrix.  The 5th solution returns a vector if x is a
> vector.
>
> 1. Matrix multiplication. Note that if x is a vector then it is treated as a
>    one column matrix.  Also note that NROW(x) is the same as nrow(x), if x is a
>    matrix; however, if x is a vector, then NROW(x) is its length while nrow(x)
>    is NULL.  Thus it is important here to use NROW and not nrow. This is
>    discussed in the help on nrow.
>
>         x %*% diag(y,NROW(x))

Not quite. The number of *columns* of x, ncol(x), is interesting here,
not NROW(x),
or just use length(y) instead of ncol(x) ....

Uwe Ligges
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._

```