Reputation: 681
Lets say I have the vector
x = [x0, x1, x2, x3] = [0, 2, 3, 1].
I want to create a symmetric matrix from x. Ie a symmetric matrix that has x as the first row and first column, with x0 as the diagonal. In other words, I want a matrix X like this:
X = [0 2 3 1] = [x0 x1 x2 x3]
[2 0 1 3] [x1 x0 x3 x2]
[3 1 0 2] [x2 x3 x0 x1]
[1 3 2 0] [x3 x2 x1 x0]
Question:
Computer science is not my area, so all of my attempts so far are quite laughable and involve loops upon loops. Am I missing something obvious?
Thank you
Upvotes: 1
Views: 972
Reputation: 34829
The trick is that the index into the input array is the sum of the indexes into the output array. For example,
output[0][3] = output[1][2] = output[2][1] = output[3][0] = input[3]
However there are two problems with this:
First the main diagonal (top/left to bottom/right) is always the first element of the input array. That can be handled as a special case by checking if the output indexes are equal.
Then there's the problem of what to do when the sum of the output indexes is more than the maximum allowed input index. In that case, the index into the input array is calculated by a subtraction, as shown in the code below.
#define SIZE 4
int input[SIZE] = {0,1,2,3};
int output[SIZE][SIZE];
for (int row = 0; row < SIZE; row++)
for (int col = 0; col < SIZE; col++)
{
if (row == col) // special case for the main diagonal
output[row][col] = input[0];
else if (row + col < SIZE) // normal case for small indexes
output[row][col] = input[row+col];
else // special case for large indexes
output[row][col] = input[2*(SIZE-1) - (row + col)];
}
Upvotes: 2