Home > Software design >  Inside the loop, write a line of code that populates the matrix M with the numbers 1 through 20
Inside the loop, write a line of code that populates the matrix M with the numbers 1 through 20

Time:09-28

I keep ending up with a matrix populated entirely by 20s. It is iterating over the number and through the indices of the matrix M but it is over writing it each time when I am looking for a matrix that is 10x2 with only unique values.

n = 20; 
M = matrix(NA, ncol = 2, nrow = 10);
a = 1
b = 1
for (i in 1:n){
    for (r in 1:nrow(M))   
        for (c in 1:ncol(M))
        i -> M[r,c]
        print(M)
}
M

CodePudding user response:

I would suggest that if the outer for-loop is indexed by increasing values to be entered as elements into the matrix, that the value of i should be used to decide which position it goes to. (If the values were not sequential then you could use the result of seq_along( your_non_consecutive_variable) as the index for the loop and the way to pick the value to be entered into the matrix. You CANNOT work with a single value set at the outer loop, and then repeat an assignment of that value multiple times with two nested inner loops.

n = 20; 
M = matrix(NA, ncol = 2, nrow = 10);
a = 1
b = 1
for (i in 1:n){
    if( i <= 10){ M[i, 1] <- i} else
        { M[i-10, 2] <- i}} 
M
#---------
     [,1] [,2]
 [1,]    1   11
 [2,]    2   12
 [3,]    3   13
 [4,]    4   14
 [5,]    5   15
 [6,]    6   16
 [7,]    7   17
 [8,]    8   18
 [9,]    9   19
[10,]   10   20

That said this is only to be used as an exercise in understanding for-loops. A more R-ish way of putting values into a matrix would be:

var <- sample(1:20)
M <- matrix( var, 2, 10)

The values in var get assigned to rows 1:10 in the first column and then rows 1:10 in the second column. R handles its matrix indexing in a column major fashion. This is important to understand when working with the results of sapply operations.

  •  Tags:  
  • r
  • Related