필터 지우기
필터 지우기

Need to get rid of an eval and loop

조회 수: 1 (최근 30일)
Christopher
Christopher 2015년 2월 3일
편집: Stephen23 2015년 2월 3일
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
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.
Summary: use a cell, structure or table to store your data, and learn about vectorization .
Stephen23
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
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.

카테고리

Help CenterFile Exchange에서 Whos에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by