0 1 2 3 4
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
So I was given this matrix and was told to create it using only for loops. What i have done so far is using cbind(0:4,1 (0:4),2 (0:4),3 (0:4),4 (0:4))
but i cant figure out a way to do so with the for function.
CodePudding user response:
You were on the right track. If you rewrite your current
cbind(0:4,1 (0:4),2 (0:4),3 (0:4),4 (0:4))
as
cbind(0 (0:4),1 (0:4),2 (0:4),3 (0:4),4 (0:4))
you might notice that the thing that you are adding to 0:4
is implicitly a loop index.
Make it explicit:
m = c()
for(i in 0:4){
m = cbind(m,i (0:4))
}
print(m)
Output:
[,1] [,2] [,3] [,4] [,5]
[1,] 0 1 2 3 4
[2,] 1 2 3 4 5
[3,] 2 3 4 5 6
[4,] 3 4 5 6 7
[5,] 4 5 6 7 8
CodePudding user response:
One way:
mat <- matrix(0L, nrow=5, ncol=5)
for (i in 0:4) {
for (j in 0:4) {
mat[i 1, j 1] <- i j
}
}
# [,1] [,2] [,3] [,4] [,5]
# [1,] 0 1 2 3 4
# [2,] 1 2 3 4 5
# [3,] 2 3 4 5 6
# [4,] 3 4 5 6 7
# [5,] 4 5 6 7 8
And technically *apply functions are loops as well:
sapply(0:4, \(x) 0:4 x)
CodePudding user response:
You can just create an empty matrix first and then fill it with two for-loops iterating over rows and columns. Playing a little bit around with the variable to write into the matrix (count
) I figured out that this is a suitable solution.
matrix2fill <- matrix(NA, 5,5)
count = 0
for (i in 1:5){
for (j in 1:5){
matrix2fill[j,i] = count
count = count 1
}
count = i
}
matrix2fill
[,1] [,2] [,3] [,4] [,5]
[1,] 0 1 2 3 4
[2,] 1 2 3 4 5
[3,] 2 3 4 5 6
[4,] 3 4 5 6 7
[5,] 4 5 6 7 8
CodePudding user response:
Try this:
a = matrix(1:25, nrow=5, ncol=5)
for (i in 1:5) {
for (j in 1:5) {
a[i][j] = (i-1) (j-1)
}
}
print(a)
CodePudding user response:
Yet another way:
mymat <- matrix(NA, nrow = 5, ncol = 5)
i_mat <- 1
for (i in 0:4) {
mymat[seq(i_mat, i_mat 4)] <- seq(i, i 4)
i_mat <- i_mat 5
}
mymat
[,1] [,2] [,3] [,4] [,5]
[1,] 0 1 2 3 4
[2,] 1 2 3 4 5
[3,] 2 3 4 5 6
[4,] 3 4 5 6 7
[5,] 4 5 6 7 8