Why the error with eval does appear in the code?

12 visualizaciones (últimos 30 días)
Lilya
Lilya el 18 de Oct. de 2015
Editada: Stephen23 el 19 de Oct. de 2015
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.

Respuesta aceptada

Stephen23
Stephen23 el 18 de Oct. de 2015
Editada: Stephen23 el 18 de Oct. de 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 comentarios
Jan
Jan el 18 de Oct. de 2015
Editada: Stephen23 el 19 de Oct. de 2015
Please, lina se, consider Stephen's advice. Make your life easier and your programs stable and efficient by avoiding the evil eval.
Lilya
Lilya el 18 de Oct. de 2015
i will

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Variables en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by