注意:如果您可以在没有' eval'的情况下指出解决方案,那就太棒了!
如果没有,我也会感恩:-)
好吧,我有一个单元格(Var_s
),它在第一行字符串和第二行矩阵中有:
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
结果必须是
Rn = 11 22 33 44
LE = 1 2 3
N = 101 102 103 104 105
答案 0 :(得分:5)
{&#34}保存结构字段作为单个变量"在docs命令{{3}}中完全涵盖了您的问题。要实现这一目标,您只需创建save()
。
要创建struct
,动态创建其字段名称,必须更改代码的大部分内容。在该循环中创建结构后,只需在循环后使用选项struct()
保存结构,然后自动为该结构中的每个字段生成一个新变量。
'-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');
如您所见,我们在该文件中存储了3个变量。