我试图使用MATLAB
中的eval
函数创建许多参数数组
基本上,我有一个大数据集(data
),我试图将其拆分为许多较小的数据集,其名称是使用循环生成的。目前,我正在使用:
variablename = ['a' num2str(academy) '_s' num2str(year) '_g' num2str(gender)];
%loop through all people, if match various classifications, write to variablename
for row = 1:totalrows;
if data(row,2) == academy;
if data(row,1) == year;
if data(row,70) == gender;
eval([variablename ' = [ data(row,8) data(row,9) data(row,73) data(row,76) data(row,77) data(row,78) data(row,79) ]; ' ]); % ; supresses output (i.e. stop it showing value of each variable
end%gender if
end%year if
end %academy if
end %row loop
这种方法运行得相当不错,除了每次我得到匹配所有if
语句的第二条记录时,它都会覆盖第一组数据。
所以我的问题是,我如何指定使用eval
创建的变量行,我要将数据写入其中?
提前致谢
答案 0 :(得分:0)
不要使用EVAL,请考虑以下事项:
data = [...]; %# some big matrix, rows are records, columns are fields
year = 2012;
gender = 2; %# female
academy = 5; %# corresponds to some meaningful value
cols = [8 9 73 76:79]; %# list of columns to select
%# get all rows matching the above conditions
idx = ( data(:,1)==year && data(:,70)==gender && data(:,2)==academy );
X = data(idx,cols);
如果您正在进行此类型的多个查询,也许您可以将结果存储在单元格数组中,并保留一个单独的矩阵来存储查询参数,例如:
map(1,:) = [2012 2 5]; %# for the above query, with X{1} containing the data
map(2,:) = [2003 1 4]; %# for another query, with X{2} for corresponding data
答案 1 :(得分:0)
回复提示,我检查了格式和以下工作
eval([variablename '(row,:) = [ data(row,8) data(row,9) data(row,73) data(row,76) data(row,77) data(row,78) data(row,79) ]; ' ]); % ; supresses output (i.e. stop it showing value of each variable