简体   繁体   中英

Matrix to vectors C++

I'm using C++.
I have the following matrix:

{1,2,3,4,5}
{6,7,8,9,10}
{11,12,13,14,15}
{16,17,18,19,20}
{21,22,23,24,25}

And i want to convert the matrix to 5 vectros as following:

a[5] = {1,6,11,16,21};
b[5] = {2,7,12,17,22};
c[5] = {3,8,13,18,23};
d[5] = {4,9,14,19,24};
e[5] = {5,10,15,20,25};

I want to convert each matrix column to vector.
I have the code that takes 5 vectors and convert it to matrix:

typedef int *pInt;
//Each element of arr is a int-type pointer
 pInt arr[5] = {a, b, c, d, e};

 int matrix[5][5] = {0};
 for(int i = 0; i < 5; ++i){
     for(int j = 0 ; j < 5; ++j){
         matrix[i][j] = arr[j][i];
     }
 }

So how can i convert the matrix to vectors?

If I got you right. For each i(line) you'll fill a different array. Something like this:

for(int i = 0; i < 5; ++i)
{
    for(int j = 0 ; j < 5; ++j)
    {
        if(i == 0)
        {
            //fill the first vector
        }
    }
}

Following code does the job:

int n=5;
int** vec = new int*[n];
for(int j=0;j<n;j++){
    vec[j] = new int[n];
    for(int i=0;i<n;i++){
        vec[j][i] = matrix[i][j];
    }
}
for(int i=0;i<n;i++){
    cout<<"Vector: "<<i<<endl;
    for(int j=0;j<n;j++){
        cout<<vec[i][j]<<" ";
    }
    cout<<endl;
}

You are creating array of integer pointers by int** vec = new int*[n]
Here, vec[j] will represent j th vector ( array ) and created by vec[j] = new int[n]

I know that you're asking for code to convert from a matrix to vectors and then those new vectors to a flipped matrix, but you can do that entire process in one step.

int n = 5;
int vec[n][n];
for(int i = 0; i < n; ++i)
{
    for(int j = 0; j < n; ++j)
    {
        vec[i][j] = matrix[j][i];
    }
}

Because you just want rows to be columns in the new matrix, all you have to do is swap the row and column iterators (ie standard notation of a matrix is matrix[row][column], so the above code iterates through the vec's first row as it also iterates through the second matrix's first column creating the inversion you wanted)

Also note that although these things are matrices and vectors in mathematics, the actual data structures you are working with are arrays and 2-D arrays(or arrays of arrays).

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