0

I would like to know how can I list the outputs of my function (it prints out vectors) so that I am able to know how many steps did it require until finding the optimal solution. I have the following code and am just wondering what should I do at the end so that when printing out the vectors, it enumerates them one at a time as well. I am new to Rstudio and do see that some operations that have to do with matrices are not common in other programming languages. I should say that I have already defined another function such as "gradient", but my concern is about the enumeration of the outputs for this particular function.

Sd=function(b0,epsilon=1e-5){
 while (norm(gradient(b0))>epsilon) {
 num1=(t(b0)%*%Q%*%gradient(b0)-t(y)%*%X%*%gradient(b0))/(t(gradient(b0))%*%Q%*%gradient(b0))
 num2=norm(num1)
 step=num2*gradient(b0)
 b0=b0-step
 print(t(b0))
  }
}

Thank you for any help I can get.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
Stiven G
  • 215
  • 2
  • 7
  • 1
    *I am new to Rstudio*...First of all, RStudio is not a programming language. Secondly, give us a minimal reproducible example regarding what you want to do and what you expect the function to perform. – DeBARtha Sep 14 '21 at 16:29

1 Answers1

0

Here's a generic answer that will show you how to approach this. Without access to your custom functions I can't give a more direct answer. It's generally helpful to give a minimal reproducible example.

That said, my basic suggestion is to use a counter variable, increment it once each loop, and include that in your printed output.

Here's a simplified example that's based on your code, but the only operation we're doing is taking repeated square roots. Note that the arrow operator <- is the best practice for assigning values. (I promise you get used to it!)

# set up a generic function for this minimal example
get_value <- function(x){
  return (sqrt(x))
}

my_function <- function(b0, epsilon = 1.1){
  # set up a counter variable
  i <- 0
  
  # our main loop
  while (get_value(b0) > epsilon) {
    # increment the counter
    i <- i + 1
    
    # do calculations
    num1 <- get_value(b0)
    
    # update our current solution
    b0 <- num1
    
    # print a message to the console with the counter and the value
    message(paste0("Iteration: ",i,"\n",
                   "b0: ", b0))
  }
  
  # print a final message to the console when we stop
  message(paste0("Final Iteration: ",i,"\n",
                 "Final b0: ", b0))
}

my_function(2)