0

If I have the following matrix for example: enter image description here

The values in the tables are an index of the elements.

for (int count =0; index<9; count++) {
     //row = function of index
     //column = function of index

}

In other words, how can I get the row and column from the index of an upper triangle of a matrix if it was ordered as in the photo.

I've been thinking about this for a while but I can't seem to figure it out!

3 Answers3

0
int i, j, v[10][10], k=0, n;
cin>>n;
for(i=0; i<n; i++)
{
     for(j=0; j<n; j++)
     if(i<j)
     {
           v[i][j]=k;
           k++;
      }
}
for(i=0; i<n; i++)
{
     for(j=0; j<n; j++)
          cout<<v[i][j]<<" ";
     cout<<endl;
}

I think this is what you want. The result should be as in your image. Tell me if you want something else. The n you write from the keyboard and it's the number of rows and columns from your matrix.

ouflak
  • 2,458
  • 10
  • 44
  • 49
  • Oh, I think I miss communicated! I'll edit the post accordingly. I meant to get the row and column from the index. The index of elements goes from 0 to 9 as in the picture. – Yousef Alnaser Nov 18 '21 at 17:12
0
int matrix[n][n];
vector<pair<int, int>> indexMap;
for(int i=0;i<n;i++)
  for(int j=i;j<n;j++)
    indexMap.push_back(make_pair(i, j));
for(int i=0;i<indexMap.size();i++)
    cout << matrix[indexMap[i].first][indexMap[i].second] << " ";

I hope this is what you are expected. You can access each element by its indexes of indexMap vector ( If n=4, indexes are from 0-9 as you mentioned in your example figure ). indexMap vector size depends on the n. Here n is the size of the matrix.

And also you can get the row and column from the index of an upper triangle of the matrix.

0
row_index(i, M):
ii = M(M+1)/2-1-i
K = floor((sqrt(8ii+1)-1)/2)
return M-1-K

column_index(i, M):
ii = M(M+1)/2-1-i
K = floor((sqrt(8ii+1)-1)/2)
jj = ii - K(K+1)/2
return M-1-jj

where M is the size of the matrix Here's a link algorithm for index numbers of triangular matrix coefficients which gives more details about the answer algebraically. credit to https://stackoverflow.com/users/4958/shreevatsar

Along with the comment from https://stackoverflow.com/users/2019794/michael-bauer