【问题标题】:save variables to a mat file by reading variable names from another mat file通过从另一个 mat 文件读取变量名称将变量保存到 mat 文件
【发布时间】:2017-11-26 12:34:48
【问题描述】:

我有一个名为 names.mat 的 mat 文件。它有变量说 var1="loop_no"、var2="phase"、var3="flow"。这些变量已经存在于基础工作区中。现在我想使用这个 mat 文件将类似名称的变量保存在另一个 mat 文件中。即,而不是在命令 save(filename,"var1","var2","var3") 中写入变量名,我希望能够在命令中的某处写入 mat 文件 names.mat 所以这些变量会自动保存在文件 results.mat 中。有可能吗?

【问题讨论】:

    标签: matlab


    【解决方案1】:

    您可以利用struct 数据类型的动态字段命名。

    • 您可以使用load 加载保存结构中变量列表的.mat 文件
    • 然后您可以使用fieldnames 函数提取变量的名称
    • 然后在forloop 中,您可以创建一个cellarray 来保存从mat 文件中读取的变量的值(这是您要保存的工作区中的变量的名称)
    • 最后一步是使用函数save 保存这个变量列表

    一种可能的实现方式是:

    % Define the variables holding the variable names
    var1='loop_no'
    var2='phase'
    var3='flow'
    % Save in a ".mat" file
    save names.mat var1 var2 var3
    % Create the variables in the Workspace
    loop_no=100
    phase=333
    flow=123.456
    % Load the file with the varaible names
    tmp_var=load('names.mat')
    % Get the names of the variables to be saved
    var_names=fieldnames(tmp_var)
    % Create a cellarray with the variables names
    for i=1:length(fieldnames(tmp_var))
       var_list{i}=tmp_var.(var_names{i})
    end
    % Save the Workspace variables in a ".mat" file
    save('new_mat_file.mat',var_list{:})
    

    测试:

    clear loop_no phase flow
    load new_mat_file.mat
    whos
    
      Name         Size            Bytes  Class     Attributes
    
      flow         1x1                 8  double              
      loop_no      1x1                 8  double              
      phase        1x1                 8  double    
    
    [loop_no;phase;flow]
    
    ans =
    
      100.0000
      333.0000
      123.4560
    

    希望这会有所帮助,

    卡普拉'

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-28
      • 2011-01-09
      • 2014-07-31
      • 1970-01-01
      • 2020-08-17
      • 2016-07-23
      • 2011-05-15
      • 1970-01-01
      相关资源
      最近更新 更多