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

如何用$readmemh指定地址读取矩阵片段存入Y_luma?

问题描述

我有一个360×640的矩阵(共230400个像素值),希望使用$readmemh命令仅读取该矩阵中的特定8×8片段,并存入Y_luma矩阵。具体需求为:将原矩阵的[8][8]至[8][15]存入Y_luma第1行,[9][8]至[9][15]存入第2行,以此类推,直到原矩阵[15][8]至[15][15]存入Y_luma第8行。

我尝试的代码如下:

module matrix_copy;

    reg [7:0] Y_luma [0:7][0:7];
    
    $readmemh("Luma_space.txt", Y_luma,

后续无法继续编写,想请教如何指定地址完成上述需求。

解决方案

方法1:先读取完整矩阵再复制目标区域

由于$readmemh仅支持读取连续的线性地址范围,无法直接提取原矩阵中分散的行片段,最直接的方式是先将整个360×640矩阵读入内存,再通过循环复制目标8×8区域:

module matrix_copy;
    // 定义原矩阵(360行×640列)
    reg [7:0] full_matrix [0:359][0:639];
    // 目标8×8矩阵
    reg [7:0] Y_luma [0:7][0:7];

    initial begin
        // 读取完整矩阵
        $readmemh("Luma_space.txt", full_matrix);
        
        // 复制目标区域:原矩阵第8-15行,第8-15列 → Y_luma第0-7行,第0-7列
        for (int row = 0; row < 8; row++) begin
            for (int col = 0; col < 8; col++) begin
                Y_luma[row][col] = full_matrix[row + 8][col + 8];
            end
        end

        // 可选:打印验证结果
        for (int i = 0; i < 8; i++) begin
            $display("Y_luma[%0d]: %h %h %h %h %h %h %h %h", 
                i, 
                Y_luma[i][0], Y_luma[i][1], Y_luma[i][2], Y_luma[i][3],
                Y_luma[i][4], Y_luma[i][5], Y_luma[i][6], Y_luma[i][7]
            );
        end
    end
endmodule

方法2:预处理文本文件提取目标片段

如果不想加载完整矩阵,可先用脚本(如Python)从原文件Luma_space.txt中提取需要的8×8元素,保存为新文件后再用$readmemh读取:

示例Python脚本(提取目标元素)

# 假设原文件每行对应矩阵的一行,元素用空格分隔
with open("Luma_space.txt", "r") as f_in, open("Y_luma.txt", "w") as f_out:
    # 跳过前8行,读取第9到16行(对应原矩阵第8到15行,索引从0开始)
    for _ in range(8):
        next(f_in)
    for _ in range(8):
        line = f_in.readline().strip().split()
        # 提取第9到16个元素(对应原矩阵第8到15列)
        target_elements = line[8:16]
        f_out.write(" ".join(target_elements) + "\n")

Verilog代码读取预处理后的文件

module matrix_copy;
    reg [7:0] Y_luma [0:7][0:7];

    initial begin
        // 直接读取预处理后的8×8元素文件
        $readmemh("Y_luma.txt", Y_luma);
        
        // 可选:打印验证结果
        for (int i = 0; i < 8; i++) begin
            $display("Y_luma[%0d]: %h %h %h %h %h %h %h %h", 
                i, 
                Y_luma[i][0], Y_luma[i][1], Y_luma[i][2], Y_luma[i][3],
                Y_luma[i][4], Y_luma[i][5], Y_luma[i][6], Y_luma[i][7]
            );
        end
    end
endmodule

关键说明

  • Verilog中二维数组的存储默认是行优先,即matrix[row][col]对应的线性地址为row * 列数 + col。
  • $readmemh的语法为$readmemh("filename", memory, start_addr, end_addr),其中start_addr和end_addr是线性地址,仅支持连续范围,无法直接跳过元素读取分散片段。

内容的提问来源于stack exchange,提问作者Sunil.B

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 15:50:46