Ex1 Carry out the regression using R.
x <- c(-.98,1,2.02,3.03,4.0)
y <- c(2.44,-1.51,-.47,2.54,7.52)
A <- matrix(c(5, sum(x), sum(x^2), sum(x), sum(x^2), sum(x^3), sum(x^2), sum(x^3), sum(x^4)), nrow=3)
B <- matrix(c(sum(y), sum((x)*y), sum((x^2)*y)))
x <- solve(A,B)
x
## [,1]
## [1,] -0.5055154
## [2,] -2.0261594
## [3,] 1.0065065
Ex2 Implement the nonlinear curve fitting for the following
data.
x <- c(0.10, 0.50, 1.0, 1.5, 2.0, 2.5)
y <- c(0.10, 0.28, 0.40, 0.40, 0.37, 0.32)
func1 <- function(params) {
a <- params[1]
b <- params[2]
residuals <- y - (x * a + b * x^2)
sum(residuals^2)
}
initial_params <- c(1, 1)
result <- optim(initial_params, func1)
a_opt <- result$par[1]
b_opt <- result$par[2]
cat("a =", a_opt, "\n")
## a = 0.554151
cat("b =", b_opt, "\n")
## b = -0.1754069
Ex3 Try to fit the following data to the nonlinear function
x <- c(0.1, 0.5, 1, 1.5, 2, 2.5)
y <- c(0, 0, 1, 1, 1, 0)
l <- function(x, a, b) {
1 / (1 + exp(a + b * x))
}
data <- data.frame(x = x, y = y)
list <- list(a=0, b=0)
model <- nls(y ~ l(x, a, b), data = data, start = list)
summary(model)
##
## Formula: y ~ l(x, a, b)
##
## Parameters:
## Estimate Std. Error t value Pr(>|t|)
## a 36.08 189726.46 0 1
## b -48.03 232780.88 0 1
##
## Residual standard error: 0.5 on 4 degrees of freedom
##
## Number of iterations to convergence: 25
## Achieved convergence tolerance: 8.639e-06