Skip to content
Prev 33783 / 63424 Next

Problem in matrix definition?

Does the following help to clarify things?
mp <- 10
  np <- 5
  a <- matrix(c(1:mp*np),mp,np)
  a
  #       [,1] [,2] [,3] [,4] [,5]
  #  [1,]    5    5    5    5    5
  #  [2,]   10   10   10   10   10
  #  [3,]   15   15   15   15   15
  #  [4,]   20   20   20   20   20
  #  [5,]   25   25   25   25   25
  #  [6,]   30   30   30   30   30
  #  [7,]   35   35   35   35   35
  #  [8,]   40   40   40   40   40
  #  [9,]   45   45   45   45   45
  # [10,]   50   50   50   50   50

  a <- matrix(c(1:50),mp,np)
  a
  #       [,1] [,2] [,3] [,4] [,5]
  #  [1,]    1   11   21   31   41
  #  [2,]    2   12   22   32   42
  #  [3,]    3   13   23   33   43
  #  [4,]    4   14   24   34   44
  #  [5,]    5   15   25   35   45
  #  [6,]    6   16   26   36   46
  #  [7,]    7   17   27   37   47
  #  [8,]    8   18   28   38   48
  #  [9,]    9   19   29   39   49
  # [10,]   10   20   30   40   50

Check what is said about precedence in '?Syntax'. The effect of
"c(1:mp*np)" is (1:mp)*np, i.e. first create (1:mp), and then
multiuply each element by np. So, with mp=10, np=5, you first get
c(1,2,3,4,5,6,7,8,9,10) from (1:10), and then
c(5,10,15,20,25,30,35,40,45,50) after multiplying this by 5.

This vector with 10 elements is then recycled 5 times over
when you ask for "a <- matrix(c(1:mp*np),mp,np)", i.e. the
equivalent of

  a <- matrix(c(5,10,15,20,25,30,35,40,45,50),10,5)

On the other hand, a <- matrix(c(1:50),10,5) does what you expected!

Hoping this helps,
Ted.
On 31-Aug-09 08:21:34, Uwe Ligges wrote:
--------------------------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at manchester.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 31-Aug-09                                       Time: 10:00:04
------------------------------ XFMail ------------------------------