Using eval versus other methods
조회 수: 9 (최근 30일)
이전 댓글 표시
Hello,
I am currently working on a script to automate some number crunching and am wondering if there is a better (more efficient) way to write the code without having to use eval.
Our main problem is using the dates in the file names as variables and being able to index correctly while performing various functions.
Thank you for your help,
Dan the Man
%load in all 1 minute averaged files and perform calculations and generate
%plots
%--------------------------------------------------------------
%define days of month in text file names, MUST BE CHANGED EVERYTIME YOU
%LOAD IN A NEW GROUP OF FILES!
day = [9, 10];
%import all text files from one directory at once
AVGfiles = dir('*AVG.txt');
for i=1:length(AVGfiles)
eval(['load ' AVGfiles(i).name ' -ascii AVG']);
end
%------------------------------------------------------------------------
for i = 1:length(AVGfiles)
j = day(i);
%define length of each file to be used in total wind calculation
eval(['k = length(Apr' num2str(j) 'AVG)'])
%compute turbulence for each minute for each text file
eval(['TKE_' num2str(j) ' = 0.5 * (Apr' num2str(j) 'AVG (:,19) + Apr' num2str(j) 'AVG (:,20) + Apr' num2str(j) 'AVG (:,21))'])
%compute total wind
for a = 1:k
eval(['total_wind_' num2str(j) '(a) = ((Apr' num2str(j) 'AVG (a,7))^2 + (Apr' num2str(j) 'AVG (a,8))^2 + (Apr' num2str(j) 'AVG (a,9))^2)^(1/2)'])
end
eval(['mph_wind_' num2str(j) ' = total_wind_' num2str(j) '/100'])
eval(['mph_wind_' num2str(j) ' = (mph_wind_' num2str(j) ' * 3600) / 1609.344'])
%compute datenumber for each file to use in plotting
eval(['datenumber_' num2str(j) ' = datenum(Apr' num2str(j) 'AVG (:,3), Apr' num2str(j) 'AVG (:,1), Apr' num2str(j) 'AVG (:,2), Apr' num2str(j) 'AVG (:,4), Apr' num2str(j) 'AVG (:,5), Apr' num2str(j) 'AVG (:,6))'])
%generate a TKE plot for each day
eval(['plot(datenumber_' num2str(j) ', TKE_' num2str(j) ')'])
datetick('x', 'mm-dd-yyyy')
ylabel('TKE')
title(['UNR Roof Apr ',num2str(j),' TKE'],'Fontsize',14)
saveas(gcf,['Apr_',num2str(j), 'TKE'], 'png')
%generate a total wind plot for each day
eval(['plot(datenumber_' num2str(j) ', mph_wind_' num2str(j) ')'])
datetick('x', 'mm-dd-yyyy')
ylabel('Wind Speed (mph)')
title(['UNR Roof Apr ',num2str(j),' Total Wind Speed'],'Fontsize',14)
saveas(gcf,['Apr_',num2str(j), 'wind'], 'png')
end
댓글 수: 0
채택된 답변
Jan
2011년 4월 20일
Convert:
eval(['load ' AVGfiles(i).name ' -ascii AVG']);
to:
Data = load(AVGfiles(i).name, '-ascii', 'AVG');
Then "Data.(['Apr', num2str(j), 'AVG'])" is much safer and more efficient than the EVAL constructions.
추가 답변 (1개)
Walter Roberson
2011년 4월 19일
eval() is the wrong approach the vast majority of the time. Please see
and
댓글 수: 0
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!