简体   繁体   中英

How to set according to the x-axis Symmetry of Matrix

I need a function that can take to according to the x-axis of symmetry of the matrix.

input (matrix[i][j]):

1 2 3
4 5 6
7 8 9

output (matrix[i][j]):

7 8 9
4 5 6
1 2 3

How can i do this on the same matrix? How should I write the inverse function?

void inverse(.......)
 {
 ..
 ..
 ..
 }

int main(){
int **matrix, i, j, k, row, column;
cout << "Row and column:" ;
cin >> row >> column;
matrix = new int*[row];
for (i=0; i<row; ++i){
    matrix[i] = new int[column];
}
cout << "input elements of matrix: " << endl;
for(i=0; i<row; i++){
         for (j=0; j<column; j++){
             cin >> *(*(matrix+i)+j);
         }
}  

inverse (........);

for(i=0; i<row; i++){
         for (j=0; j<column; j++){
             cout << *(*(matrix+i)+j);
         }
         cout << endl;
}  
return 0;
}

In this particular case, you can modify the loop to print the matrix backwards:

for(i = 0; i < row; i++) {

->

for(i = row - 1; i >= 0; i--) {

But if you want to actually do something to the data, my suggestion would be to refactor this code to use std::vector .

std::vector<std::vector<int> > matrix(numberOfRows, std::vector<int>(numberOfColumns));
// You can use std::vector<std::valarray<int> > matrix; alternatively.

You would then flip it simply by using an STL function:

std::reverse(matrix.begin(), matrix.end());

Edit:
Well, if you don't want to use std::vector for the time being and for this particular case, what you would do is this:

void flipMatrix(int** matrix, int rows, int columns) {
    int middle = rows/2; // I expect it to truncate for an odd number of rows.

    // Temporary row for swapping
    int* tempRow;

    for (int i = 0; i < middle; i++) {
        // swap rows
        tempRow = matrix[i];
        matrix[i] = matrix[rows - i - 1];
        matrix[rows - i - 1] = tempRow;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM