MATLAB: How do i use eval function when the sentence has apostrophe (‘) in it

apostropheeval

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?

Best Answer

An apostrophe, or rather a single quote as it is called, in a string can be accomplished by doubling it, like in:
str = 'it''s me!'
More importantly, you do not want to use eval at all, by designing your variables a little bit more clever using, e.g., cell arrays or structs.
B(1).values = sinc(x).*sinc(y);
B(2).values = sinc(2x).*sinc(2y); % note that 2x is invalid syntax, but I do no know what you mean!
% B(3).values = . . . etcetera
for k = 1:numel(B)
filename = sprintf('B_%d.bmp',k)
imwrite(B(k).values, filename)
end
This away you avoid all the complications induced by eval ...