Need to get rid of an eval and loop

2 views (last 30 days)
Christopher
Christopher on 3 Feb 2015
Edited: Stephen23 on 3 Feb 2015
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 Comments
Stephen23
Stephen23 on 3 Feb 2015
Edited: Stephen23 on 3 Feb 2015
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.
Summary: use a cell, structure or table to store your data, and learn about vectorization .
Stephen23
Stephen23 on 3 Feb 2015
Edited: Stephen23 on 3 Feb 2015
And of course i and j are the names of the inbuilt imaginary unit , so they should not be used for loop variable names.

Sign in to comment.

Answers (1)

Titus Edelhofer
Titus Edelhofer on 3 Feb 2015
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.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!