-2

Well, I have searched a lot of questions but nothing works. Here is my question, I was asked to create a matrix like this

#      [,1] [,2] [,3] [,4] [,5]
# [1,]    1    2    3    4    5
# [2,]    2    3    4    5    6
# [3,]    3    4    5    6    7
# [4,]    4    5    6    7    8
# [5,]    5    6    7    8    9

using the rep(), matrix() and seq() function.

I want to add 1 to each repeating cycle in seq(1:5) for 5 times, but I don't know how to. Would any one help me with this question?

user20650
  • 24,654
  • 5
  • 56
  • 91
Liu Oreo
  • 29
  • 2
  • Show us what you tried so far (code and output). Otherwise people will downvote/vote-to-close this heavily for lack of effort (*"Give me teh codez"*). – smci Aug 10 '16 at 01:22
  • hint:: have a look at the `each` argument of `rep`, while noticing that R uses vector recycling (for example, you can add a longer vector to a shorter one `1:2 + c(0,0,1,1)`) Once you have generated the sequence chuck it in a matrix call – user20650 Aug 10 '16 at 01:33
  • 1
    Another: `m = matrix(, 5, 5); row(m)+col(m)-1L` – Frank Aug 10 '16 at 02:48

3 Answers3

2

Thank you @user20650 ! I finally figured it out.(Excuse me for not being familiar with Stack-overflow's functions)

I use the code like this:

a = matrix(rep((1:5),each = 5),5,5,byrow = TRUE)
b = matrix(rep((0:4),each = 5),5,5)
a+b

And it works

Liu Oreo
  • 29
  • 2
  • 1
    well done... another way using the recycling is `matrix(1:5, ncol=5, nrow=5) + rep(0:4, each=5)` – user20650 Aug 10 '16 at 01:47
  • Since the request included using `seq()`, this might also be an option: `matrix(rep(seq(5)-1,each=5)+rep(seq(5),5),5)`. It's the same as the solution suggested by @user20650, only written in a slightly different way. – RHertel Aug 10 '16 at 02:09
  • your `a` is essentially `row()` function and `b` is `col()` – Ott Toomet Aug 10 '16 at 03:09
2
n = 5
r = seq(1,n)
matrix(rep(r,n),n,n,byrow = T) + r - 1

or alternatively, if you don't need to use the stipulated functions

n = 5
r = 1:n
t(matrix(-1,n,n) + r) + r
Nicholas Hamilton
  • 10,044
  • 6
  • 57
  • 88
1

Check col() and row():

a <- matrix(0, 5, 5)
col(a) + row(a) - 1
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    2    3    4    5
[2,]    2    3    4    5    6
[3,]    3    4    5    6    7
[4,]    4    5    6    7    8
[5,]    5    6    7    8    9
Ott Toomet
  • 1,894
  • 15
  • 25