0
votes

I have a mat file called names.mat. It has variables say var1="loop_no", var2="phase", var3="flow". These variables are already present in the base workspace. now i want to use this mat file to save similarly names variables in another mat file. i.e instead of writing variable names in the command save(filename,"var1","var2","var3") I want to be able to write the mat file names.mat somewhere in the command so that these variables are automatically saved in the file results.mat. Is it possible?

1

1 Answers

0
votes

You can exploit the dynamic field naming of the struct data type.

  • You can load the .mat file holding the list of variable in a struct by using load
  • then you can extract the names of the variables using the fieldnames function
  • then in a forloop you can create a cellarray holding the value of the variables read from the mat file (which are the names of the variables in theWorkspace you want to save)
  • the last step is to save this list of varaibles with the functnio save

A possible implementatin couls be:

% 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{:})

A test:

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

Hope this helps,

Qapla'