2017-06-23 114 views
0

我有一個名爲names.mat的mat文件。它有變量說var1 =「loop_no」,var2 =「階段」,var3 =「流量」。這些變量已經存在於基礎工作區中。現在我想使用這個mat文件在另一個mat文件中保存類似的名稱變量。即,而不是在命令save(filename,「var1」,「var2」,「var3」)中寫入變量名稱我希望能夠在命令的某處寫入mat文件names.mat,以便這些變量自動保存在文件results.mat中。可能嗎?通過讀取另一個mat文件中的變量名將變量保存到mat文件中

回答

0

您可以利用struct數據類型的動態字段命名。

  • 您可以通過使用load
  • 那麼你可以使用fieldnames函數提取變量的名稱
  • 然後在forloop你可以創建一個加載.mat文件保存在一個結構體變量列表cellarray保存從mat文件中讀取的變量的值(它們是要保存的工作區中變量的名稱)
  • 最後一步是將該變量列表保存爲函數save

一種可能implementatin couls是:

% 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 

希望這有助於

Qapla」

相關問題