使用C创建仅存储矩阵的行索引和列索引的稀疏矩阵

时间:2018-12-21 11:33:59

标签: c linear-algebra

我有一个(2 x 4)二进制矩阵A,我想用(2 *比例x 4 *比例)二进制矩阵B替换该矩阵,以使矩阵A中的元素1被(比例x比例)替代单位矩阵和元素0替换为(比例x比例)零矩阵。

matrix A:
1 0 1 0
0 1 0 0

matrix B:
1 0 0 0 1 0 0 0
0 1 0 0 0 1 0 0
0 0 1 0 0 0 0 0
0 0 0 1 0 0 0 0

但是我只需要在矩阵B中放置1的位置,因此我创建了一个稀疏矩阵,仅存储矩阵B的行索引和列索引。

0, 0
0, 4
1, 1
1, 5
2, 2
3, 3

对于下面的示例代码,我分两个步骤进行操作:(1)创建矩阵B(2)创建稀疏结构。 这是一个示例代码,其中定义的宏仅用于此示例,通常,我使用10000 x 10000或更高阶的巨大矩阵。

我想避免第1步(即创建矩阵B),而直接创建稀疏结构来存储行和列索引。有人可以帮我吗?

#include <stdio.h>

#define rowSize         2       //!< row size of matrixA
#define colSize         4       //!< column size of matrixA
#define scalingFactor   2       //!< scaling factor to increase the size of matrixA
#define nonZeros        3       //!< number of 1's in matrixA

//!< struct to hold the position of 1's in matrixB
typedef struct sparseMatrix{
    int row;
    int col;
}sparseMatrix;

int main()
{
    int row, col, idx;
    int matrixA[rowSize][colSize] = {{1,0,1,0},{0,1,0,0}};
    int matrixB[rowSize*scalingFactor][colSize*scalingFactor] = enter image description here;
    sparseMatrix matrixC[nonZeros*scalingFactor];

    // check for the element 1 in matrixA and replace it with an identity matrix of size 'scalingFactor'
    for(row = 0; row < rowSize; row++){
        for(col = 0; col < colSize; col++){
            if(matrixA[row][col] == 1){
                for (idx = 0; idx < scalingFactor; idx++){
                    matrixB[(scalingFactor) * row + idx][(scalingFactor) * col + idx ] = 1; // matrixB created
                }
            }
        }
    }

    // create a sparse matrix that stores only position of 1's in matrixB
    idx = 0;
    for(row = 0; row < rowSize*scalingFactor; row++){
        for(col = 0; col < colSize*scalingFactor; col++){
            if(matrixB[row][col] == 1){
                matrixC[idx].row = row;
                matrixC[idx].col = col;
                idx++;
            }
        }
    }


    // print the sparse matrix
    for(idx = 0; idx < nonZeros*scalingFactor; idx++){
            printf("%d, %d\n",matrixC[idx].row, matrixC[idx].col);
    }

    return 0;
}

1 个答案:

答案 0 :(得分:2)

我相信您可以将第二个for循环集成到第一个循环中。因此,与其创建矩阵B,不如直接保存其索引:

int i = 0; // variable to save matrixC current index

// check for the element 1 in matrixA and replace it with an identity matrix of size 'scalingFactor'
for (row = 0; row < rowSize; row++) {
    for (idx = 0; idx < scalingFactor; idx++) {
        for (col = 0; col < colSize; col++) {
            if (matrixA[row][col] == 1) {
                // instead of creating a temporary dense matrix,
                // just save its indexes:
                matrixD[i].row = row * scalingFactor + idx;
                matrixD[i].col = col * scalingFactor + idx;
                i++;
            }
        }
    }
}