The gauss
function takes 3 parameters:
- a pointer to the matrix of coefficients
- the number of variables
- a pointer to matrix of solution
#include <stdio.h>
#include <stdlib.h>
int gauss(double* matrix , int x, double* sol);
int main(){
int x;
scanf("%i",&x);
double *mat = malloc((x+1)*x*sizeof(double)), *sol =(malloc(x*sizeof(double)));
for(int i=0;i<(x+1)*x; i++) scanf("%lf",&mat[i]);
int state = gauss(mat, x, sol);
if (state ==0) for(int i=0;i<x;i++) printf("X%i = %lf\n",i,sol[i]);
else printf("The system has %s%s", state==-1 ? "infinte number of":"no","solution(s)");
free(mat);
free(sol);
return 0;
}
int gauss(double* matrix , int x, double* sol){
for(int i=0;i<x-1;i++)for(int j=i+1; j<x; j++) for(int k =x;k>=0;k--){
matrix[j*(x+1)+k] -= matrix[i*(x+1)+k]*matrix[j*(x+1)+i]/matrix[i*(x+2)];
}
if(matrix[x*(x+1)-2 ] ==0){
if(matrix[x*(x+1)-1]==0) return -1;
return 1;
}
sol[x-1]= matrix[(x-1)*(x+1)+x]/matrix[(x-1)*(x+1)+x-1];
for(int i =x-2; i>=0; i--){
double counter=0;
for(int j=x-1;j>i;j--) counter+= matrix[i*(x+1)+j] *sol[j];
sol[i] = (matrix[i*(x+1)+x]-counter) / matrix[i*(x+2)];
}
return 0;
}
I was wondering what I can do to make the code shorter (keeping the good style), with better performance and with better memory consumption.
I used linear matrix because I simply don't know how to declare multidimensional array with malloc
and I don't know how to pass it as a parameter to function.
I used indent -kr -i8 -l1000 -lc1000
for styling and I used preprocessor for simplifying the matrix math but some pieces make no sense as as matrix(x, -2)
:
#include <stdio.h>
#include <stdlib.h>
#define matrix(i,j) matrix[i*(x+1)+j]
int gauss(double *matrix, int x, double *sol);
int main()
{
int x;
scanf("%i", &x);
double *mat = malloc((x + 1) * x * sizeof(double)), *sol = (malloc(x * sizeof(double)));
for (int i = 0; i < (x + 1) * x; i++)
scanf("%lf", &mat[i]);
int state = gauss(mat, x, sol);
if (state == 0)
for (int i = 0; i < x; i++)
printf("X%i = %lf\n", i, sol[i]);
else
printf("The system has %s solutions", state == -1 ? "infinte number of" : "no");
free(mat);
free(sol);
return 0;
}
int gauss(double *matrix, int x, double *sol)
{
for (int i = 0; i < x - 1; i++)
for (int j = i + 1; j < x; j++)
for (int k = x; k >= 0; k--)
matrix(j, k) -= matrix(i, k) * matrix(j, i) / matrix(i, i);
if (matrix(x, -2) == 0) {
if (matrix(x, -1) == 0)
return -1;
return 1;
}
sol[x - 1] = matrix((x - 1), x) / matrix((x - 1), (x - 1));
for (int i = x - 2; i >= 0; i--) {
double counter = 0;
for (int j = x - 1; j > i; j--)
counter += matrix(i, j) * sol[j];
sol[i] = (matrix(i, x) - counter) / matrix(i, i);
}
return 0;
}
Is there anything I can do to make this code better?