我有几个表,每个表都有大量数据(每个20MB)。我们将它们称为Table_1,Table_2,Table_3等。这些表的结构类似,具有相同的列标题(但行数不同)。我们说Attribute_A,Attribute_B等
我有兴趣为每个表在Attribute_B上执行计算。这些计算涉及循环Attribute_B。
我首先创建一个包含所有表名的主列表。
Table_List = [Table_1, Table_2, ... Table 10];
现在我可以迭代这个并执行我的计算。使用eval和我的列向量名称作为Current_Table值的函数进行单个计算就可以正常工作了:
for Current_Table = Table_List
Peak_Value = max(eval(strcat(Current_Table,"Attribute_C")));
当我执行需要迭代列向量的计算时,我遇到了麻烦。例如,以下内容失败。
for Current_Table = Table_List
for i = 1:length(eval(strcat(Current_Table,".Attribute_B")
X = X + eval(strcat(Current_Table,".Attribute_B"))(i);
当我尝试将评估列与i的所需索引值结合时,MATLAB会挂起。有没有办法做到这一点?
我理解如果我将所有数据的单个结构制作得更容易(不使用字符串列表但实际上组合了数据)。我想迭代遍历每个表而不重写数据。
答案 0 :(得分:0)
正如excaza指出的那样,在这类问题中使用eval
是非常不鼓励的。一种更安全,更优雅的方法是使用结构。
以下是一个对您有用的程序示例
clear
% Intialize the structure that will hold all the tables
TABLES = struct;
% List of table names
table_names = {'Table_1' 'Table_2' 'Table_3'};
% Number of tables
nTables = length(table_names);
% Fill the tables with some data
% TABLES can also be nested structures with more than one data item in them in
% each substructure
for itb=1:nTables
% TABLES.(table_names{itb}) = rand(3);
% Load from files with names Table_N.txt
TABLES.(table_names{itb}) = load([table_names{itb},'.txt']);
end
% Perform operations on the components
for jtb=1:nTables
% Using a temporary array
% temp = [];
% temp = TABLES.(table_names{jtb});
% A(jtb) = max(max(temp));
% B(jtb) = temp(2,1);
% .. and such
% Or directly
A(jtb) = max(max(TABLES.(table_names{jtb})));
B(jtb) = TABLES.(table_names{jtb})(2,1);
end
您有一个名称列表,您可以使用它们来创建嵌套结构或其他任何东西 - 比如此处的数组 - 在名为TABLES
的主结构内部。您可以从文件中填充此数据,在这种情况下,我只使用rand
。收集数据及其上的任何操作都可以通过循环完成。在第二个循环中,您有一个示例,您可以使用临时数组直接或间接地操作数据。
这是一个相对宽泛的主题,所以请随意提问,我会将它们添加到我的答案中。