【问题标题】:Matlab cells with Names具有名称的 Matlab 单元格
【发布时间】:2015-01-16 21:19:12
【问题描述】:

注意:如果你能指出一个没有“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

【问题讨论】:

  • 请保留代码的代码格式,并将您的文本说明放在代码格式之外,以备将来的问题使用(并且可能相应地编辑此问题)。

标签: string matlab for-loop cell names


【解决方案1】:

“将结构字段保存为单个变量”下的docssave() 命令几乎完全涵盖了您的问题。要到达那里,您只需创建 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');

现在让我们看看,我们存储了什么:

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

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

如您所见,我们在该文件中存储了 3 个变量。

【讨论】:

  • 优秀的答案!有用!很多时候发生的事情是我不知道在哪里可以找到 Matlab 帮助中的解释。谢谢
  • @JohnazGrynn 很高兴为您提供帮助。由于您是本网站的新手:当出现解决您问题的答案时,您可以接受该答案。
猜你喜欢
  • 2013-01-27
  • 1970-01-01
  • 1970-01-01
  • 2018-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-16
  • 1970-01-01
相关资源
最近更新 更多