Matlab:循环中的变量系列

时间:2013-05-09 19:33:51

标签: matlab variables loops

这是另一个帮助我的stackoverflow参与者的解决方案。 数据来自csv文件:

    States Damage Blizzards

    Indiana 1      3
    Alabama 2      3
    Ohio    3      2
    Alabama 4      2


%// Parse CSV file
[States, Damage, Blizzards] = textread(csvfilename, '%s %d %d', ...
    'delimiter', ',', 'headerlines', 1);

%// Parse data and store in an array of structs
[U, ix, iu] = unique(States);        %// Find unique state names
S = struct('state', U);              %// Create a struct for each state
for k = 1:numel(U)
    idx = (iu == k);                 %// Indices of rows matching current state
    S(k).damage = Damage(idx);       %// Add damage information
    S(k).blizzards = Blizzards(idx); %// Add blizards information
end

在MATLAB中,我需要在循环中创建一系列指定的变量(A1,A2,A3)。所以我的结构S有3个字段:州,龙卷风,飓风。

现在我尝试使用此方法来分配A1 =,A2 =,我收到错误,因为它不适用于结构:

   for n = 1:numel(S)
   eval(sprintf('A%d = [1:n]',S(n).states));
   end

输出目标是循环到结构字段的一系列指定变量:

  A1 = 2 3
  A2 = 2 3
  A3 = 4 5

1 个答案:

答案 0 :(得分:1)

我不是百分百肯定我理解你的问题 但也许你正在寻找这样的东西:

for n = 1:numel(S)
   eval(sprintf('A%d = [S(n).damage S(n).blizzards]',n));
end

使用evalc而不是eval的BTW将抑制命令行输出。

一点解释,为什么

eval(sprintf('A%d = [1:n]',S(n).state));  

不起作用:

S(1).state  

返回

ans = 
   Alabama

这是一个字符串。然而,

A%d

需要一个数字(有关数字格式,请参阅this) 另外,

numel(S) 

产量

ans = 
   3

因此,

eval(sprintf('A%d = [1:n]',n));

将只返回以下输出:

A1 =

 1

A2 =

 1     2

A3 =

 1     2     3  

因此,您希望n作为变量名的计数器,但是再次使用其他结构域(damageblizzards)中的条目的向量组合n作为反击。