Why the error with eval does appear in the code?

1 次查看(过去 30 天)
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.

采纳的回答

Stephen23
Stephen23 2015-10-18
编辑:Stephen23 2015-10-18
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 个评论
Jan
Jan 2015-10-18
编辑:Stephen23 2015-10-19
Please, lina se, consider Stephen's advice. Make your life easier and your programs stable and efficient by avoiding the evil eval.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Variables 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by