user4103008
user4103008

Reputation:

Matlab cells with Names

Note: Please if you can point a solution without 'eval', that would be great!!! If not, I'll be thankful too :-) Well, I have a cell (Var_s) that has in the first row strings and in the second row matrices:

clc
clearvars
fclose all

L=[11 22 33 44];
M=[1 2 3];
N=[101 102 103 104 105, 95 96 97 98 99];
Var_s=cell(2,3);
Var_s(1,1:3)={'Rn', 'LE', 'O'}; %// The strings are all different and were not created in a loop. 
Var_s(2,1:3)={L, M, N};         %// No correlation is possible.


%//Than I delete all variables because I can work with the cell (Var_s{2,:}) 
%//to execute some computations
clearvars L M N


%//Now I want to save the values which are stored inside of the cells in the 
%//second line of Var_s, Var_s{2,:}, associating to them the names in the first
%//row of the Var_s, Var_s{1,:}, in a .mat file
%//But let's imagine that instead of having size(Var_s{2,:})=3 I would have
%//something like 1000 (but lets keep it simple for now having just 3). 
%//Consequently I want to use a 'for' to do this work! 
%//And it is at this point that the issue appears. How can I use the strings
%//inside Var_s{1,:} to create variables and store them in the .mat file with
%//the values in the cells of Var_s{2,:} associated to them?


filename='Clima';
a=0;
save(filename,'a'); %//Creats the file with a variable a=0


for i=1:length(Var_s(2,:))
genvarname(Var_s{1,i})=Var_s{2,i}; %//The idea is to create a variable using a stringn and associate the values 
save(filename,char(Var_s{1,i}),'-append'); %//The idea is to add the created variable that has the same name in Var_s{1,i}
end
clearvars


%//After all this I could access the variables that are stored in 'Clima.mat' 
%//by their name such as
load('Clima.mat')
Rn
LE
O

And the result must be

  Rn = 11 22 33 44
  LE = 1 2 3
  N = 101 102 103 104 105

Upvotes: 1

Views: 98

Answers (1)

Nras
Nras

Reputation: 4311

Your question is pretty much fully covered in the docs to the save() command under "Save Structure Fields as Individual Variables". To get there, you only must create that struct.

To create that struct(), where you dynamically create its field names, not much of your code must be changed. Once your struct is created in that loop, just save the struct once after the loop with the option '-struct', which automatically then generates a new variable for each field in that struct.

s = struct();
for i=1:length(Var_s(2,:))
    s.(Var_s{1,i})=Var_s{2,i}; % struct with dynamic field names
end
save(filename, '-struct', 's');

Now let's see, what we stored:

whos('-file', 'Clima.mat')
  Name      Size            Bytes  Class     Attributes

  LE        1x3                24  double              
  O         1x10               80  double              
  Rn        1x4                32  double 

As you can see, we stored 3 variables in that file.

Upvotes: 5

Related Questions