# Nested loops n = 10 for (i in 1:n){ # control statement for the outer loop cat("count to ", i, "\n") # indent the statements of the outer loop 4 spaces for ( j in 1:i){ # control statement for the inner loop cat(" ", j) # indent 4 more spaces for the inner loop # no "\n" here so all these are on the same line. } # curley to end the inner loop, indented 4+2 spaces cat(" -- done!\n") # statement in the body of the outer loop, indent 4 } # close of the outer loop, indent 2 # Create A, a specific 3 X 3 matrix c1 = c(1, 2, 3) # column 1 c2 = c(1, 1, 1) # column 2 c3 = c(0, 1, 1) # column 3 A = matrix( cbind( c1, c2, c3), nrow=3, ncol=3) cat("\n Print A, row by row\n\n") cat("Row 1 of A is ", A[1,1:3], "\n") cat("Row 2 of A is ", A[2,1:3], "\n") cat("Row 3 of A is ", A[3,1:3], "\n") # Create D, a diagonal n X n matrix with D[i,i] = i n = 3 # the size of the matrix d_list = 1:(n^2) # create a list of n^2 numbers, which will be the matrix entries D = matrix(d_list, n) # re-arrange these numbers into an n X n matrix # other languages (Matlab, Python) have easier ways to do this. cat("\n Print D, row by row\n\n") cat("Row 1 of D is ", D[1,1:3], "\n") cat("Row 2 of D is ", D[2,1:3], "\n") cat("Row 3 of D is ", D[3,1:3], "\n") # Zero out the entries of D, use a nested loop (also called double loop) for ( i in 1:n){ # start of the outer loop for ( j in 1:n){ # start of the inner loop D[i,j] = 0 } # end of the inner loop } # end of the outer loop cat("\n Print D, row by row\n\n") cat("Row 1 of D is ", D[1,1:3], "\n") cat("Row 2 of D is ", D[2,1:3], "\n") cat("Row 3 of D is ", D[3,1:3], "\n") # Set the diagonal entries of D for ( i in 1:n){ D[i,i] = i } cat("\n Print D, row by row\n\n") cat("Row 1 of D is ", D[1,1:3], "\n") cat("Row 2 of D is ", D[2,1:3], "\n") cat("Row 3 of D is ", D[3,1:3], "\n") x = c(4, 5, 6) y = D %*% x cat("\n y is",y, "\n") for ( i in 1:n){ sum = 0 for ( j in 1:n){ sum = sum + A[i,j]*x[j] } y[i] = sum } cat("\n y is",y, "\n")