How do i use eval function when the sentence has apostrophe (') in it?
Afficher commentaires plus anciens
I'm trying to use eval function with for loop
B1=sinc(x).*sinc(y);
B2=sinc(2x).*sinc(2y);
B3=sinc(3x).*sinc(3y);
B4=sinc(4x).*sinc(4y);
B5=sinc(5x).*sinc(5y);
for i=1:5
s=['imwrite(B' num2str(i) ','B_' num2str(i) '.bmp')']
eval(s);
end
But this sentence does not make sense since in some elements in "s" there are 3 apostrophe,
which is impossible for computer to compute.
Also, imwrite function got to have apostrophe for file name....
how do i make a breakthrough?
2 commentaires
Ugh. Do NOT use eval for such trivial code.
See Jos's answer below for the best way to do this (best in the sense faster, neater, less buggy, more efficient, easier to debug, more secure).
Réponse acceptée
Plus de réponses (3)
Jos (10584)
le 28 Fév 2014
Modifié(e) : Jos (10584)
le 28 Fév 2014
This is one of the reasons you should not use eval:
eval(char('fkur*)Ykvj"GXCN"{qw"pgxgt"mpqy"yjcv"jcrrgpu0"Kv"eqwnf"jcxg"hqtocvvgf"{qwt"jctfftkxg"000)+'-2)) ;
2 commentaires
Derrick Lim
le 28 Oct 2019
Modifié(e) : Derrick Lim
le 28 Oct 2019
Out of curiosity, what exactly does that command do? (Too scared to actually try it out)
Steven Lord
le 28 Oct 2019
Just run the part of that command starting with "char(" and ending with the closing parenthesis for the char function call. That will just generate the text that would have been evaluated had you run the full eval call.
Jacob Halbrooks
le 27 Fév 2014
Modifié(e) : Jacob Halbrooks
le 27 Fév 2014
If you need EVAL, I'd suggest using SPRINTF to form your expression. This lets you see the command you are writing more naturally and makes apostrophe management a little easier:
for i=1:5
s = sprintf('imwrite(%s, ''%s'')', ...
['B' num2str(i)], ['B_' num2str(i) '.bmp']);
eval(s);
end
3 commentaires
Jos (10584)
le 27 Fév 2014
You (almost) never need eval ...
Hoon
le 28 Fév 2014
Stephen23
le 11 Déc 2017
@Hoon: use Jos's answer. It is the better way of solving this problem.
Iain
le 28 Fév 2014
Heres a third answer....
apostrophe = char(39);
then just use apostrophe
And a fourth answer:
If you actually want an apostrophe, and not a string start/termination character, you can use other apostrophes.
E.g, Alt+0145 = ‘ and Alt+0146 = ’
Catégories
En savoir plus sur Parallel and Cloud dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!