是否可以打印以下列方式格式化的代码:
Iteration 1:
# A matrix goes here
Iteration 2:
# Another matrix goes here
Iteration 3:
# Another...
Iteration 4:
# Last matrix
# Final matrix is printed again
如果我的变量verbose为true,我的函数应该以这种方式打印。所有矩阵都存储在列表中。这是我的代码:
converge <- function(A, eps = 1e-6, itmax = 100, verbose = TRUE) {
counter <- 1
iterations <- list()
B0 <- compute.B(A, 1)
iterations[[1]] <- B0
if (itmax == 1) {
return(B0)
}
for (i in 2:itmax) {
B1 <- compute.B(A, i)
if (sqrt(sum((B1 - B0)^2)) < eps) {
break()
}
B0 <- B1
iterations[[i]] <- B1
counter <- counter + 1
}
# Shows last four iterations
if (verbose && counter >= 4) {
for (i in (counter - 3):counter) {
print(iterations[[i]])
}
}
return(B1)
}
答案 0 :(得分:0)
使用paste
格式化输出。例如,您可以这样做:
cat(paste(paste("Iteration", i,":"), ## Iteration i:
round(iterations[[i]],2), ## the matrix i
sep='\n') ## in a new line