Reputation: 939
The following code is returning 4 matrices -
n <- 5
for(i in range(n)){
square_n = n*n
for (j in range(n)){
str1 = matrix(1:square_n, byrow=TRUE, nrow=n)
print(str1)
}
}
However when when I move the print(str1) "outside" the loop, it prints just one matrix (which is what I want). However what I'm doing calls for the print statement to be inside the loop. How do I correct my code.
Upvotes: 0
Views: 31
Reputation: 887148
It is just updating the 'str1' on each iteration and the value we get is from the last iteration. print
is just printing the value on the console on each iteration. If we want to store it, then have to create a list
str1 <- vector('list', 5)
Inside the loop, change the assignment line to
str1[[i]] <- matrix(1:square_n, byrow = TRUE, nrow = n)
print(str1[[i]])
-full code
for(i in range(n)){
square_n = n*n
for (j in range(n)){
str1[[i]] = matrix(1:square_n, byrow = TRUE, nrow = n)
print(str1[[i]])
}
}
Upvotes: 1