简体   繁体   English

从C中的给定向量创建对称矩阵的例程

[英]Routine For Creating A Symmetric Matrix From A Given Vector In C

Lets say I have the vector 可以说我有向量

x = [x0, x1, x2, x3] = [0, 2, 3, 1]. 

I want to create a symmetric matrix from x. 我想从x创建一个对称矩阵。 Ie a symmetric matrix that has x as the first row and first column, with x0 as the diagonal. 即一个对称矩阵,其中x为第一行和第一列,x0为对角线。 In other words, I want a matrix X like this: 换句话说,我想要这样的矩阵X:

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: 题:

  1. How can I do this in C? 我该如何在C语言中执行此操作?
  2. How can I extend this for any length vector given? 如何将其扩展为给定的任何长度向量?

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 谢谢

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)];
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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