fjac writing problem in usrfun function


madmat88
08-19-2008, 04:15 AM
Hi,

I try to use the Newton Raphson method to resolve a system. I use the method describe in chapter 9.6, and the function mnewt.
I must define my matrix fjac in the usrfun function.
My problem is I don't know how I must write this matrix.

I try with
void usrfun(double *x,int n, double *fvec, double **fjac)
{
int j;
for (j=0;j<(n*n);j++){
fjac[j]=1; /*for example*/
}
}

or I try
for (j=0;j<n;j++){
for (k=0;k<n;k++){
fjac[j][k]=1;
}
}

But the both solutions make problem

Someone knows how to define a matrix in C code for numerical recipes?

Best regard

Mathias

davekw7x
08-19-2008, 09:38 AM
...I try to...

In Numerical Recipes C programs, vectors and matrices are one-based, not zero-based. The most straightforward way to use vectors and matrices for the Numerical Recipes C functions is detailed in section 1.2 of the book. Use the NR functions vector() and matrix()

For example

/* Parameters of the problem */
#define MAXSTEPS 5
#define N 4
#define TOLX 1.0e-6
#define TOLF 1.0e-6


void usrfun(float *x, int n, float *fvec, float **fjac)
{
int i, j;

for (i = 1; i <= n; i++) {
for (j = 1; j <= n; j++) {
fjac[i][j] = /* whatever */
}
}
for (i = 1; i <= n; i++) {
fvec[i] = /* whatever */
}
}

int main(void)
{
int i;

float **fmat;
float *fvec;
float *x;

fmat = matrix(1, N, 1, N);
fvec = vector(1, N);
x = vector(1, N);

/* Set up the starting vector */
for (i = 1; i <= N; i++) {
x[i] = /* whatever */
}

/* Apply Newton-Raphson a maximum of MAXSTEPS steps */
mnewt(MAXSTEPS, x, N, TOLX, TOLF);

/* Calculate final values of fvec using x from mnewt */
usrfun(x, N, fvec, fmat);

for (i = 1; i <= N; i++) {
/*
* Show values of x and fvec, or do whatever
* you want to do with the results.
*/
}

free_vector(x, 1, N);
free_vector(fvec, 1, N);
free_matrix(fmat, 1, N, 1, N);

return 0;
}


Regards,

Dave