Matheus Augusto
Matheus Augusto

Reputation: 11

Segmentation Fault C++ Matrix

I want make any matrix[n][n+1] become an upper triangular matrix[n][n+1].

I did this code but that causes a segmentation fault.

void diagonalizarMatriz(float** Matriz, int n){
for(int i = 0; i < n-1; i++)
    for(int k = 0; k < n; k ++)
        for(int j = n; j >= i; j++)
            Matriz[k][j] = Matriz[k][j] - ((Matriz[k][i] * Matriz[i][j]) / Matriz[i][i]);
}

int main(){
float** Matriz = new float* [3];
for(int i = 0; i < 3 ; i++)
    Matriz[i] = new float [4];

//test matrix
Matriz[0][0] = 1;
Matriz[0][1] = 4;
Matriz[0][2] = 52;
Matriz[0][3] = 57;
Matriz[1][0] = -27;
Matriz[1][1] = -110;
Matriz[1][2] = -3;
Matriz[1][3] = -134;
Matriz[2][0] = 22;
Matriz[2][1] = 2;
Matriz[2][2] = 14;
Matriz[2][3] = 38;

diagonalizarMatriz(Matriz, 3);

Upvotes: 1

Views: 138

Answers (2)

BAS
BAS

Reputation: 155

UPDATE

Assuming your question is about diagonalizing a matrix (as Eugene claims in the comment section):

In addition to what Yunnosch pointed out, diagonalizing a matrix means that the matrix must be a square n x n. However, in main you're initializing it to be a 3 x 4 matrix.

Original code

float** Matriz = new float* [3];
for(int i = 0; i < 3 ; i++)
  Matriz[i] = new float [4];

To get rid of the segfault, change the following part in main (set matrix to 3 x 3):

float** Matriz = new float* [3];
for(int i = 0; i < 3 ; i++)
  Matriz[i] = new float [3];

//test matrix
Matriz[0][0] = 1;
Matriz[0][1] = 4;
Matriz[0][2] = 52;
Matriz[1][0] = -27;
Matriz[1][1] = -110;
Matriz[1][2] = -3;
Matriz[2][0] = 22;
Matriz[2][1] = 2;
Matriz[2][2] = 14;

Finally, to get the following matrix (lower-triangular):

1 0 0
4 5 0
7 8 9

Remove the equal sign from your third nested loop:

for(int j = n; j > i; j--)

I assume from here you can work your way through this, to make it an upper-triangular matrix.

OLD ANSWER

Try this:

int matrix[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
int row = 3;
int col = 3;
int i, j; 
for (i = 0; i < row; i++) { 
  for (j = 0; j < col; j++) {
    if (i > j) { 
        cout << "0" << " "; 
    } else
        cout << matrix[i][j] << " "; 
  } 
  cout << endl; 
}

Will give you this matrix

1 2 3
0 5 6
0 0 9

Upvotes: 0

Yunnosch
Yunnosch

Reputation: 26703

Here

for(int j = n; j >= i; j++)

you start with n at the upper border of the dimensions of your array and the count up,
very soon you therefor access beyond your array, which gets you a segfault if you are lucky.

At a guess you want

for(int j = n; j >= i; j--)

to count down.

Upvotes: 1

Related Questions