Domanda

Hello I am trying to make an inverse function for a tridiagonal matrix in c, but my code is giving me a segfault error. The code is

/* Inverse of a n by n matrix */
#include<stdio.h>
#include<math.h>
#include<stdlib.h>

double J[3][3];

double phi(i, n)
{
double p;
if(i==n)
{
    return 1; 
}
else if(i==n-1)
{
    return J[i][i];
}
else
{
    p=J[i][i]*phi(i+1,n)-J[i][i+1]*J[i+1][i]*phi(i+2,n);
}
return p;
}

double theta(i,n)
{
double p;
if(i==-1)
{
    return 1;
}
else if(i==0)
{
    return J[i][i];
}
else
{
    p=J[i][i]*theta(i-1,n)-J[i-1][i]*J[i][i-1]*theta(i-2,n);
}
return p;
}

void main(void)
{
double T[3][3];
int n=3;
int i, j, a, b;
J[0][0]=1;
J[0][1]=1;
J[0][2]=0;
J[1][0]=2;
J[1][1]=2;
J[1][2]=2;
J[2][0]=0;
J[2][1]=2;
J[2][2]=2;
for(i=0; i<n;i++);
{
    for(j=0; j<n;j++)
    {
    b=j;
    a=i;
    if(i<j)
    {
        T[i][j]=pow(-1, i+j);
        for(a; a<b; a++)
        {
            T[i][j]*=J[a][a+1];
        }
        T[i][j]*=theta(i-1,n)*phi(j+1)/theta(n-1,n);
    }
    else if(i==j)
    {
        if(i==0)
        {
            T[i][j]=0;
        }
        else
        {
            T[i][j]=theta(i-1,n)*phi(j+1,n)/theta(n-1,n);
        }
    }
    else
    {
        T[i][j]=pow(-1, i+j);
        for(b; b<i; b++)
        {
            T[i][j]*=J[a][b];
        }
        T[i][j]*=theta(j-1, n)*phi(i+1,n)/theta(n-1, n);
    }
    }
}

for(i=0;i<n;i++)
{
    for(j=0;j<n;j++)
    {
        printf("%lf\n", T[i][j]);
    }
}
}   

The J matrix in there is just an example matrix, I will be implementing this code into another one that calls a matrix to this function.

È stato utile?

Soluzione

First thing, your should replace your function signature double phi(i, n) by double phi(int i, int n). The same goes for the theta function. Also, in your code, you have written this line : T[i][j]*=theta(i-1,n)*phi(j+1)/theta(n-1,n); Your phi function should take 2 parameters, so maybe you wanted this :

T[i][j]*=theta(i-1,n)*phi(j+1, n)/theta(n-1,n);

I would also suggest you to use T[i][j]=pow((double)(-1), (double)(i+j));. You can see the signatures of pow here.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top