如何转置存储为C 1D数组的2D矩阵 [英] How to Transpose 2D Matrix Stored as C 1D Array

查看:93
本文介绍了如何转置存储为C 1D数组的2D矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个二维矩阵

1 2 3
4 5 6
7 8 9

像这样存储在C中

int array[9] = {1,2,3,4,5,6,7,8,9};

我想像这样得到矩阵的转置

and I would like to get the transpose of that matrix like this

int array_t[9] = {1,4,7,2,5,8,3,6,9};

无需将原始数组转换为2D数组.该怎么办?

without converting the original array into a 2D one. How can this be done?

推荐答案

这可以通过切换通常用于为其编制索引的循环来完成.如果您想要原始矩阵,则可以使用类似的方法遍历它

This can be done by switching around the loops you would normally use to index it. If you wanted the original matrix you could loop through it with something like this

for (i = 0; i < 3; ++i) {
    for (j = 0; j < 3; ++j) {
        printf("%d ", array[j + i * 3]);
    }
    printf("\n");
}

如果我们切换ij循环,我们将获得所需的输出,如以下示例程序所示

If we switch the i and j loops we can get the desired output as in the following sample program

#include <stdio.h>

int main() {
    int array[9] = {1, 2, 3, 4, 5, 6, 7, 8, 9};

    int i, j;

    for (j = 0; j < 3; ++j) {
        for (i = 0; i < 3; ++i) {
            printf("%d ", array[j + i * 3]);
        }
        printf("\n");
    }
}


这与2D矩阵的转置的数学定义有关.在2D矩阵上的转置操作将行与列交换,在C程序中对它进行索引时,我们交换行和列循环.


This is related to the mathematical definition of the transpose of a 2D matrix. The transpose operation on a 2D matrix swaps the rows with the columns, in the C program when we are indexing it we swap our row and column loops.

这篇关于如何转置存储为C 1D数组的2D矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆