I use nleqslv to solve a nonlinear equation in R. The constant b is a list of values from "21.csv". There are 10137 values of b, so I want to get 10137 roots of this function (10137 values of x). Why the result of x has only one value (the length of x is 1 )? Is there anything wrong with the code, and how to get the list of 10137 values of x with the 10137 b(s)? Thanks
a=read.csv("21.csv",header=TRUE)
b=c(a$c)
library(nleqslv)
target= function(x, a=1.239448)
{
y = numeric(1)
y[1] = -a*(1+exp(a*x[1]-b))^(-2)*exp(a*x[1]-b)*x[1]-a+b
y
}
xstart = c(10)
target(xstart)
nleqslv(xstart, target, control=list(ftol=.0001, allowSingular=TRUE),jacobian=TRUE,method="Newton")
>
$x
[1] 9.68385
> head(a)
c
1 11.83898
2 11.72014
3 14.86955
4 18.20404
5 17.69610
6 17.51668
> head(b)
[1] 11.83898 11.72014 14.86955 18.20404 17.69610 17.51668
As I mentioned in my comment your function target
is always returning a scalar and xstart
is a scalar. If b
is a vector then you should rewrite target
, return a vector and provide a starting value of appropriate length. See the following.
Write the target
function as follows as a function of a vector x
and returning a vector
target <- function(x, a=1.239448)
{
y <- numeric(length(x))
y <- -a*(1+exp(a*x-b))^(-2)*exp(a*x-b)*x-a+b
y
}
Create some fake data for b
and set some values for xstart
b <- c(1.5,1.6)
xstart <- c(1,2)
nleqslv(xstart, target, control=list(ftol=.0001, allowSingular=TRUE),jacobian=TRUE,method="Newton")
Result is now
$x
[1] 0.8771918 2.9811141
$fvec
[1] 0.000000e+00 2.960259e-08
$termcd
[1] 1
$message
[1] "Function criterion near zero"
$scalex
[1] 1 1
$nfcnt
[1] 6
$njcnt
[1] 4
$iter
[1] 4
$jac
[,1] [,2]
[1,] -0.3627487 0.0000000
[2,] 0.0000000 0.2279917
Method Broyden
also works and the control
argument is not needed in this case.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.