Why the error with eval does appear in the code?

2 views (last 30 days)
hi all,
The file names are in the format of JDA00912.ohh which contains: JDA0, 0, years 9-13, months 1-12 For the single numbers, it should be 01,02,03,...etc And for the year 2009 it should be 09, the others= 10,11,12,13
I wrote the following code by using eval function and the following error was appearing clear
FN1 = 'JDA0';
z = '0';
yr = 10;
mn = 12;
yr = 9:13;
ext = '.ohh';
FN2 = [FN1'; num2str(yr(1,:))'; z'; num2str(mn(1,:))'; ext']';
eval (['fid=fopen(', FN2, ')']);
how can I solve this problem?
Error: Unexpected MATLAB expression.
Thank you.

Accepted Answer

Stephen23
Stephen23 on 18 Oct 2015
Edited: Stephen23 on 18 Oct 2015
Using eval for such trivial code like this is a really really bad idea, because you remove all of MATLAB's inbuilt code checking and code hinting tools. Do yourself a favor and learn how to program without eval. Doing so makes your code more faster, more robust and less obfuscated. Read this to know why eval is a really bad programming tool, even though beginners seem to think that it is the greatest tool ever:
In your case your code probably does not do what you think it does, and this is being exacerbated by using eval. If you look at the value of FN2 it is a very unusual filename:
>> FN2
FN2 = JDA09 10 11 12 13012.ohh
I suspect that you really wanted to do something in a loop like this:
FN1 = 'JDA0';
z = '0';
mn = 12;
yr = 9:13;
ext = '.ohh';
for k = 1:numel(yr)
tmp = sprintf('%s%02d%d%02d%s',FN1,yr(k),z,mn,ext)
fid = fopen(tmp,'rt');
... other code here
end
Summary Do NOT use eval for such trivial code. And use sprintf to generate the filename from the numbers. Read its documentation to know what formatting options it has.
  2 Comments
Jan
Jan on 18 Oct 2015
Edited: Stephen23 on 19 Oct 2015
Please, lina se, consider Stephen's advice. Make your life easier and your programs stable and efficient by avoiding the evil eval.

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!