Hello,

I'd like to fit a user defined function to a data set, but I have problems
to find my problem. The user defined function is a combination of two
rectangular functions, and the listing below gives an example for what I
want to do. The problem is, that I get the error message for fit1 and fit2
"Error in nlsModel(formula, mf, start, wts) : singular gradient matrix at
initial parameter estimates".  traceback() shows "stop("singular gradient
matrix at initial parameter estimates")" as the last step in both cases, so
I assume, that I make a fundamental mistake, because start values should be
OK. So my two questions are:

1) How do I fit only one parameter as tried with fit1 in the example?

2) How do I fit all parameters as tried with fit2 in the example?

Thanks,

Dirk



rm(list=ls(all=TRUE))

# rectangular function
g <- function (x, x0=0, P=1, w=0.5) {
    .g <- function(.x, .x0=x0, .P=P, .w=w) {
        .x <- .x - (.x %/% .P)*.P
        if ( (.x >= x0 ) & (.x <= .x0 + .w) ) {return(1)} else
{return(0)}
    }
    return( unlist(lapply(x, .g)))
}

# combining two rectangular functions with an offset dx
f <- function (x, x0=0, P=2, w=0.5, dx=1) {
    .f <- function(.x, .dx=dx, .P=P, .w=w)
        g(x=(x0+.x), P=.P, w=.w) + g(x=(x0+.x+dx), P=.P, w=.w)
    return( unlist(lapply(x, .f)))
}

# generate a data set
dataset <- curve(f(x, dx=0.65), 1, 5, n=1e3)
# add some noise
dataset$x <-  dataset$x + rnorm(1e3, 0, 0.02)
dataset$y <-  dataset$y + rnorm(1e3, 0, 0.05)
points(dataset, type='p', cex=0.67, col='blue')


# trying to fit only one parameter
fit1 <- nls(
        y ~ f(x, x0=0, P=2, w=0.5, dx),
        start = list(dx=0.6),
        data = dataset
)

# trying to fit all parameters
fit2 <- nls(
        y ~ f(x),
        start = list(x0=0, P=2, w=0.5, dx=0.6),
        data = dataset
)

	[[alternative HTML version deleted]]

