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!
CodePudding user response:
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.
CodePudding user response:
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.
CodePudding user response:
Thank you guys for the answers!
Here's a link algorithm for index numbers of triangular matrix coefficients which gives the answer algebraically. credit to https://stackoverflow.com/users/4958/shreevatsar
Along with the comment from https://stackoverflow.com/users/2019794/michael-bauer