Search code examples
matlabioprintf

Can anyone give me some explanations about fprintf('How about single quote('')?\n') in MATLAB?


>> fprintf('How about single quote('')?\n')
How about single quote(')?

the output is the same as:

>> fprintf("How about single quote(\')?\n")
How about single quote(')?

which is more general to comprehend (Escape character is composed of a backslash'\' and a character(e.g. 'n'))

So, is a backslash('\') can be altered by a single quote( ' ) to represent escape character in MATLAB?


Solution

  • Matlab has char vectors and strings. They are different data types. Char vectors are enclosed with single quotes ('):

    disp('This is a char vector')
    

    whereas strings use double quoutes ("):

    disp("Hey, I am a string")
    

    To introduce a single quote in a char vector, or a double quote in a string, you duplicate it:

    disp('Hey, what''s up?')
    disp("Say ""Hi""")
    

    Introducing a double quote in a char vector, or a single quote in a string, poses no problem:

    disp('She said "yes"')
    disp("What's the matter?")
    

    All this applies normally when the char vectors or strings are used as arguments to fprintf. Additionally, Matlab's fprintf and sprintf apparently1 understand \' as synonymous of ', and \" as synonymous of "; but the duplication rules still apply.2 So these are equivalent:

    fprintf('I don''t like strings\n')
    fprintf('I don\''t like strings\n')
    

    as are these:

    fprintf("""Inconceivable!"", he retorted\n")
    fprintf("\""Inconceivable!\"", he retorted\n")
    

    Outside of fprintf or sprintf, \' and \" don't have those special meanings. Try

    disp('\'' \"')
    disp("\' \""")
    

    1 I haven't been able to find this documented.
    2 The reason is probably to mimic C's fprintf behaviour; but note that no duplication is needed there.