Help on Selection - fprintf __ Functions (MATLAB®)

Embed Size (px)

Citation preview

  • fprintfWrite data to text fileSyntax

    fprintf(fileID, format, A, ...)fprintf(format, A, ...)count = fprintf(...)

    Descriptionfprintf(fileID, format, A, ...) applies the format to all elements of array Aand any additional array arguments in column order, and writes the data to a text file. fprintf uses the encoding scheme specified in the call to fopen.fprintf(format, A, ...) formats data and displays the results on the screen.count = fprintf(...) returns the number of bytes that fprintf writes.

    Input ArgumentsfileID One of the following:

    An integer file identifier obtained from fopen.1 for standard output (the screen).2 for standard error.

    Default: 1 (the screen)

  • format String in single quotation marks that describes the format of the output fields.Can include combinations of the following:

    Percent sign followed by a conversion character, such as '%s' forstrings.Operators that describe field width, precision, and other options.Literal text to print.Escape characters, including:'' Single quotation mark%% Percent character\\ Backslash\a Alarm\b Backspace\f Form feed\n New line\r Carriage return\t Horizontal tab\v Vertical tab\xN Hexadecimal number, N\N Octal number, N

    Conversion characters and optional operators appear in the following order(includes spaces for clarity):

    The following table lists the available conversion characters and subtypes.

    Value Type Conversion DetailsInteger, signed %d or %i Base 10 values

    %ld or %li 64bit base 10 values%hd or %hi 16bit base 10 values

  • Integer, unsigned %u Base 10%o Base 8 (octal)%x Base 16 (hexadecimal), lowercase

    letters af%X Same as %x, uppercase letters AF%lu%lo%lx or %lX

    64bit values, base 10, 8, or 16

    %hu%ho%hx or %hX

    16bit values, base 10, 8, or 16

    Floatingpointnumber

    %f Fixedpoint notation%e Exponential notation, such as

    3.141593e+00%E Same as %e, but uppercase, such

    as 3.141593E+00%g The more compact of %e or %f,

    with no trailing zeros%G The more compact of %E or %f,

    with no trailing zeros%bx or %bX%bo%bu

    Doubleprecision hexadecimal,octal, or decimal valueExample: %bx prints pi as 400921fb54442d18

    %tx or %tX%to%tu

    Singleprecision hexadecimal,octal, or decimal valueExample: %tx prints pi as 40490fdb

    Characters %c Single character%s String of characters

    Additional operators include:Field widthMinimum number of characters to print. Can be a number, or an asterisk(*) to refer to an argument in the input list. For example, the input list ('%12d', intmax) is equivalent to ('%*d', 12, intmax) .Precision

  • For %f, %e, or %E: Number of digits to the right of the decimalpoint.Example: '%6.4f' prints pi as '3.1416'

    For %g or %G Number of significant digits.Example: '%6.4g' prints pi as ' 3.142'

    Can be a number, or an asterisk (*) to refer to an argument in the inputlist. For example, the input list ('%6.4f', pi) is equivalent to ('%*.*f', 6, 4, pi) .Flags

    Action Flag ExampleLeftjustify. %-5.2fPrint sign character (+ or ). '+' %+5.2fInsert a space before the value. ' ' % 5.2fPad with zeros. '0' %05.2fModify selected numeric conversions:

    For %o, %x, or %X, print 0, 0x, or 0Xprefix.For %f, %e, or %E, print decimalpoint even when precision is 0.For %g or %G, do not remove trailingzeros or decimal point.

    '#' %#5.0f

    IdentifierOrder for processing inputs. Use the syntax n$, where n represents theposition of the value in the input list.For example, '%3$s %2$s %1$s %2$s' prints inputs 'A', 'B', 'C'as follows: C B A B .

    The following limitations apply to conversions:Numeric conversions print only the real component of complex numbers.If you apply an integer or string conversion to a numeric value thatcontains a fraction, MATLAB overrides the specified conversion, anduses %e.If you apply a string conversion (%s) to integer values, MATLAB:

    Issues a warning.Converts values that correspond to valid character codes tocharacters. For example, '%s' converts [65 66 67] to ABC.

    Different platforms display exponential notation (such as %e) with a

  • Different platforms display exponential notation (such as %e) with adifferent number of digits in the exponent.

    Platform ExampleWindows 1.23e+004UNIX 1.23e+04

    Different platforms display negative zero (-0) differently.

    Conversion CharacterPlatform %e or %E %f %g or

    %GWindows 0.000000e+000 0.000000 0Others 0.000000e+00 0.000000 0

    A Numeric or character array.

    ExamplesPrint multiple values and literal text to the screen:

    B = [8.8 7.7 ; ... 8800 7700];fprintf('X is %4.2f meters or %8.3f mm\n', 9.9, 9900, B)

    MATLAB displays:X is 9.90 meters or 9900.000 mmX is 8.80 meters or 8800.000 mmX is 7.70 meters or 7700.000 mm

    Explicitly convert doubleprecision values with fractions to integer values, and print to thescreen:

    a = [1.02 3.04 5.06];fprintf('%d\n', round(a));

    Write a short table of the exponential function to a text file called exp.txt :

    x = 0:.1:1;y = [x; exp(x)];

    % open the file with write permission

  • fid = fopen('exp.txt', 'w');fprintf(fid, '%6.2f %12.8f\n', y);fclose(fid);

    % view the contents of the filetype exp.txt

    MATLAB import functions, all UNIX applications, and Microsoft Word and WordPadrecognize '\n' as a newline indicator. However, if you plan to read the file with MicrosoftNotepad, use '\r\n' to move to a new line when writing. For example, replace theprevious call to fprintf with the following:

    fprintf(fid, '%6.2f %12.8f\r\n', y);

    On a Windows system, convert PCstyle exponential notation (three digits in the exponent)to UNIXstyle notation (two digits), and print data to a file:

    a = [0.06 0.1 5 300]

    % use sprintf to convert the numeric data to text, using %ea_str = sprintf('%e\t',a)

    % use strrep to replace exponent prefix with shorter versiona_str = strrep(a_str,'e+0','e+');a_str = strrep(a_str,'e-0','e-');

    % call fprintf to print the updated text stringsfid = fopen('newfile.txt','w');fprintf(fid, '%s', a_str);fclose(fid);

    % view the contents of the filetype newfile.txt

    Display a hyperlink (The MathWorks Web Site) on the screen:

    site = 'http://www.mathworks.com';title = 'The MathWorks Web Site';

    fprintf('%s\n', site, title)

    References[1] Kernighan, B. W., and D. M. Ritchie, The C Programming Language, Second Edition,PrenticeHall, Inc., 1988.[2] ANSI specification X3.1591989: "Programming Language C," ANSI, 1430 Broadway,New York, NY 10018.

  • See Alsodisp | fclose | ferror | fopen | fread | fscanf | fwrite | sprintfHow To

    Formatting StringsAppending or Overwriting Existing Files

    Was this topic helpful? Yes No

    19842010 The MathWorks, Inc. Terms of Use Patents Trademarks Acknowledgments