这是另一位帮助我的计算器参与者的解决方案。 数据从一个CSV文件来:Matlab:循环中的变量系列
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:状态,龙卷风,飓风。
现在,我已经尝试这种方法来分配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
我不确定这是否是'Matlab-way'的处理方式,如[解决] [这里] – Schorsch 2013-05-09 19:53:15
@ user1608954为什么你需要一堆不同名称的变量?为什么不在该结构中创建另一个字段,或者至少使用[单元格阵列](http://www.mathworks.com/help/matlab/cell-arrays.html)? – 2013-05-09 20:06:09
那么,我正在生成一个不同的变量名称,所以我可以绘制不同的变量。 Schorsch,这里是一个结构:S = struct('Texas',0,'Kansas',1,'Maryland',2) – user1608954 2013-05-09 20:16:47