Need to get rid of an eval and loop
1 次查看(过去 30 天)
显示 更早的评论
I have the code
Fe = zeros(maxthick,numfiles);
for i=1:numfiles
eval(sprintf('tnum = numel(data%d.results(:,13));',i));
for j=2:tnum
eval(sprintf('Fe(j,i)=(data%d.results(j,13)-data%d.results(j-1,13))-(abspor(j,i)-abspor(j-1,i));',i,i));
end
end
where tnum=8000 and numfiles=441.
The line:
for j=2:tnum
eval(sprintf('Fe(j,i)=(data%d.results(j,13)-data%d.results(j-1,13))-(abspor(j,i)-abspor(j-1,i));',i,i));
end
is extremely expensive. This should be made into a vectorized procedure, but the eval is making it complicated. How can this be improved?
2 个评论
Stephen23
2015-2-3
编辑:Stephen23
2015-2-3
A classic example of why using eval to generate sequential variable names is really poor programming practice. Do not do this. Dynamically assigning variable names is a really bad idea in MATLAB:
The best alternatives are to keep your data in an array (e.g. as they are returned from your file-reading function), or if you require key-value access to your data then use a structure . Structures do allow dynamic fieldnames , and this is much more robust than dynamic variables.
If you have a newer version of matlab you can also use a table , which stores the data together in one array but also allows key-name access to the columns.
Stephen23
2015-2-3
编辑:Stephen23
2015-2-3
And of course i and j are the names of the inbuilt imaginary unit , so they should not be used for loop variable names.
回答(1 个)
Titus Edelhofer
2015-2-3
Hi,
to start with, I would suggest to do a
data_i = eval(sprintf('data%d', i));
at the very beginning of the i-loop and then you work with data_i and no further eval/sprintf.
Titus
PS: I assume you "have" to work with the variables data1, data2, etc. If you have control over their creation, I would recommend to use a cell array data{1}, data{2}, ... to get fully rid of the eval constructs.
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!