You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

稀疏矩阵快速转置程序输出异常,请求排查修正方案

稀疏矩阵快速转置C程序错误排查与修复

首先明确你的输入矩阵结构:
原矩阵是2行3列,非零元素为:

  • (0,0): 3
  • (0,2):5
  • (1,1):4

转置后的目标矩阵应为3行2列,每行元素对应原矩阵的列元素:

  • 行0:[3, 0] → 原列0的元素
  • 行1:[0, 4] → 原列1的元素
  • 行2:[5, 0] → 原列2的元素

你的实际输出明显是元素位置匹配错误,快速转置的核心错误通常出在列统计、位置计算、元素转置赋值这三个环节,以下是具体排查点和修复方案:

常见错误点

  • num数组统计错误:num数组应该统计原矩阵每一列的非零元素个数,如果误统计成行的个数,会导致pos数组计算错误
  • pos数组计算错误:pos[0] = 0,pos[col] = pos[col-1] + num[col-1],如果颠倒了num的下标或者初始值错误,会导致转置元素的存放位置偏移
  • 转置元素赋值错误:原矩阵元素(row, col, val)转置后应为(col, row, val),如果误写成(row, col, val),会导致行列颠倒
  • 输出逻辑错误:输出转置矩阵时,没有按行遍历,或者误按原矩阵的列顺序输出错误的元素

修复后的示例代码

#include <stdio.h>

#define MAX_SIZE 100

typedef struct {
    int row, col, val;
} Triple;

void fastTranspose(Triple src[], Triple dest[], int rows, int cols, int nums) {
    int num[MAX_SIZE] = {0};
    int pos[MAX_SIZE] = {0};
    int i, col;

    // 统计每列的非零元素个数
    for (i = 0; i < nums; i++) {
        col = src[i].col;
        num[col]++;
    }

    // 计算每列第一个非零元素在转置矩阵中的位置
    pos[0] = 0;
    for (col = 1; col < cols; col++) {
        pos[col] = pos[col-1] + num[col-1];
    }

    // 完成转置
    for (i = 0; i < nums; i++) {
        col = src[i].col;
        dest[pos[col]].row = src[i].col;
        dest[pos[col]].col = src[i].row;
        dest[pos[col]].val = src[i].val;
        pos[col]++;
    }
}

void printMatrix(Triple trans[], int transRows, int transCols, int nums) {
    int i, j, k = 0;
    // 按行输出转置后的矩阵
    for (i = 0; i < transRows; i++) {
        for (j = 0; j < transCols; j++) {
            if (k < nums && trans[k].row == i && trans[k].col == j) {
                printf("%d ", trans[k].val);
                k++;
            } else {
                printf("0 ");
            }
        }
        printf("\n");
    }
}

int main() {
    Triple src[MAX_SIZE] = {
        {0, 0, 3},
        {0, 2, 5},
        {1, 1, 4}
    };
    Triple dest[MAX_SIZE];
    int rows = 2, cols = 3, nums = 3;
    int transRows = cols, transCols = rows;

    fastTranspose(src, dest, rows, cols, nums);
    printMatrix(dest, transRows, transCols, nums);

    return 0;
}

代码说明

  1. num数组统计:遍历原矩阵的所有非零元素,按列统计个数,确保每列的元素数量正确
  2. pos数组计算:从第1列开始,累加前一列的元素个数,得到当前列第一个元素在转置矩阵中的起始位置
  3. 转置赋值:将原元素的行和列交换后存入转置矩阵的对应位置,同时更新pos数组的指针
  4. 输出逻辑:按转置矩阵的行和列顺序遍历,遇到非零元素则输出,否则输出0,确保格式符合预期

运行上述代码后,输出将与你的预期一致:

0 3 
4 0 
0 5

内容的提问来源于stack exchange,提问作者Harshal Malani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 14:21:14