0

I am have a multi-dimensional array that needs to be resolved, to solve for the unknown values (x1,x2,x3,..). In this multi-dimensional array, my array size in the i and j coordinate are different; B[n][n+1]. I know this Basic C, Gauss Jordan Method to solve for the unknown, is incorrect and would like someone to point in how to modify it..

This code is accurate for an Array with the same n values only; eg. A[n][n].

//Computation to solve
for(j=0; j<=n; j++)
{
    for(i=0; i<=n; i++)
    {
        if(i!=j)
        {
            c=B[i][j]/B[j][j];                    
            for(k=0;k<=n+1;k++)
            {
                B[i][k] = B[i][k] - c*B[j][k];
            }
        }
    }
}

//Print Solution
printf("\nThe solution is:\n");
for(i=0; i<=n; i++)
{
    x[i]=B[i][n+1]/B[i][i];
    printf("\n x%d=%.3f\n",i,x[i]);
}

An example would be if my n=2. The array that i would want to solve is B[2][3].

0  -20  0  -1
0  30  -10  0
0  -10  10  1

The output of this code is

x1= -inf 
x2=0.050
x3=0.000

The correct output should be

x1=0.00
x2=0.05
x3=0.15
Cherry_thia
  • 696
  • 1
  • 10
  • 24

1 Answers1

0

This code is accurate for an Array with the same n values only; eg. A[n][n].

No, the code already accounts for column n+1 (which holds the right-hand constant terms) in the loop

            for(k=0;k<=n+1;k++)
            {
                B[i][k] = B[i][k] - c*B[j][k];
            }

(since k runs up to n+1). So, it is correct in this regard.

An example would be if my n=2. The array that i would want to solve is B[2][3].

C arrays are declared by specifying the number of elements in the array, not the highest index, so you want B[3][4].

The main fault of the shown code is its lack of the row swapping operation, which may be necessary if B[j][j] is zero, and the related test. We can implement that by inserting

        if (!B[j][j])
        {
            for (i=j+1; i<=n; i++)
                if (B[i][j]) { swap(B[j], B[i]); break; }
            if (!B[j][j]) continue; // leave all-zero column as is
        }

at the beginning of the for(j=0; j<=n; j++) loop body (implementing swap() left to the reader).

The correct output should be

x1=0.00

Whether this is correct is debatable, but if you want a variable where every number is a solution to take the value zero, you may insert

        if (B[i][i] == 0 && B[i][n+1] == 0) x[i] = 0;

before the printf("\n x%d=%.3f\n",i,x[i]).

Armali
  • 18,255
  • 14
  • 57
  • 171