【问题标题】:How to reference a variable from a mat file numerically in MatLab?如何在 MatLab 中以数字方式引用 mat 文件中的变量?
【发布时间】:2013-06-11 13:22:07
【问题描述】:

我正在为 MatLab 编写一个脚本,其中使用 load 命令将 *.mat 文件加载到工作区。我的问题是我不确定如何引用变量名。我知道基于大小命令我需要什么数据,但我需要一种以数字方式引用变量的方法。也许像列表中第一个这样的索引的索引为 1 或其他东西。有没有办法做到这一点?

提前致谢

【问题讨论】:

  • “数字引用”是什么意思?你的意思是array indexing
  • 所以一个例子是我加载一个 mat 文件,它有 3 个变量。名称可能因加载的 mat 文件而异,但文件之间的大小相同。因此,我试图避免将名称硬编码到我的脚本中,并且更愿意执行类似“工作区中的 temp = 2nd 变量”之类的操作,这样我就不需要知道运行代码的具体名称。这有帮助吗?

标签: matlab variables


【解决方案1】:

您的描述不是很清楚,您的意思是要通过索引访问从 MAT 文件加载的变量吗?类似于以下内容:

%# load all variables of MAT-file in a structure
S = load('myfile.mat');
fn = fieldnames(S);

%# get a variable by index
idx = 1;
x = S.(fn{idx})

当然,如果变量名先排序会更有意义:fn = sort(fn)

【讨论】:

    【解决方案2】:

    您可以使用whos 查看.mat 文件的内容。例如:

    %Create some data in a file
    cd(tempdir);
    x=rand(5,5);
    y=rand(6,6);
    save someFile x y
    
    %Then look at the variable metadata within that file.
    varMeta = whos('-file','someFile')
    varMeta = 
    2x1 struct array with fields:
        name
        size
        bytes
        class
        global
        sparse
        complex
        nesting
        persistent
    

    然后您可以在 size 字段上应用所需的任何逻辑来确定您要查找的变量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-02
      • 1970-01-01
      • 1970-01-01
      • 2012-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多