help-gsl
[Top][All Lists]

## [Help-gsl] 2D nonlinear least squares function

 From: Ansgar Philippsen Subject: [Help-gsl] 2D nonlinear least squares function Date: Tue, 13 Apr 2004 11:06:44 +0200

```Hi

```
I want to fit a set of parameters to a 2D model function z=f(x,y; a_1,..,a_n). To this end, I would like to use the nonlinear least squares fitting routines provided by gsl.
```
```
Please pardon my ignorance, but are the solvers only designed to fit a 1D function, or can one use arbitrary dimensions? I have come up with the following approach (pseudocode modified after the example in the documentation):
```
<code>

struct data {
size_t nx,ny;
double* z; // pointer to values of 2D function
double* sigma; // dito for sigmas
};

```
int f(const gsl_vector* x, void* params, gsl_vector* f)
```{
size_t nx = ((struct data *)params)->nx;
size_t ny = ((struct data *)params)->ny;
double *z = ((struct data *)params)->y;
double *sigma = ((struct data *) params)->sigma;

// extract parameters from x
double a0 = gsl_vector_get(x,0);
double a1 = gsl_vector_get(x,1);

for(size_t xi=0;xi<nx;++xi) {
for(size_t yi=0;yi<ny;++yi) {
int indx = yi*nx+xi;
// calculate Fxy based on parameters
double Fxy = calc_something(xi,yi,a0,a1);
gsl_vector_set(f, indx, (Fxy - z[indx])/sigma[indx]);
}
}
return GSL_SUCCESS;
}

// and the rest accordingly...

</code>

Should this work in principle?

Thank you in advance - Ansgar

======================================
Ansgar Philippsen, PhD
MIH - Biozentrum - Basel - Switzerland
http://www.mih.unibas.ch

```