# # Rosenbrock function for lecture "Numerical Optimization". # # Author: Sangkyun Lee (sangkyun.lee@tu-dortmund.de) # # # Helper functions # # Create a column vector (matrix with a single column in R) for the given list l. # Ex. x = vec(c(1.2, 2.4)) vec <- function(l) { len = length(l); v <- matrix(l, nrow=len, ncol=1); return(v) } # Create a matrix for the given list l with the given number of rows(r) and column(r) # Ex. x = mat(c(1,2,3,4), 2, 2) mat <- function(l, r, c, byrow=TRUE) { len = length(l); if(!(len = r*c)) { print("Error in mat(): length of l must be r x c") return (NULL); } m <- matrix(l, nrow=r, ncol=c, byrow=byrow); return(m) } # # Compute the inverse of a square matrix A # inv <- function(A) { return(solve(A)) } # # Compute the 2-norm of a vector or a matrix # norm2 <- function(A) { return(norm(A, type="2")) } # # Rosenbrock function (function value, gradient, and Hessian) for a given x = (x1,x2). # x must be a column vector (a 2x1 matrix in R) # f <- function(x) { if (!(class(x)=="matrix" && nrow(x)==2 && ncol(x)==1)) { print("Error in f(x): x must be 2x1 matrix"); return (NULL); } x1 = x[1]; x2 = x[2]; val = 100*(x2-x1^2)^2 + (1-x1)^2; return(val); } g <- function(x) { if (!(class(x)=="matrix" && nrow(x)==2 && ncol(x)==1)) { print("Error in f(x): x must be 2x1 matrix"); return (NULL); } x1 = x[1]; x2 = x[2]; val = vec( c( -400*(x2-x1^2)*x1 - 2*(1-x1), 200*(x2-x1^2) ) ) return(val) } H <- function(x) { if (!(class(x)=="matrix" && nrow(x)==2 && ncol(x)==1)) { print("Error in f(x): x must be 2x1 matrix"); return (NULL); } x1 = x[1]; x2 = x[2]; val = mat( c( -400*(x2-3*x1^2)+2, -400*x1, -400*x1, 200 ), 2, 2 ) return(val) }