Main Content

print

Class: matlab.automation.streams.OutputStream
Namespace: matlab.automation.streams

Write text generated by plugin to output stream

Description

example

print(stream,formatSpec,A1,...,An) writes formatted data to the output stream. The method uses the formatSpec formatting operators to format the data that a plugin, such as a TestRunnerPlugin instance, generates in arrays A1,...,An.

For data that is not generated by a plugin, use fprintf to write the data to a text file or the screen, or use sprintf to format the data into a string or character vector.

Input Arguments

expand all

Location where the plugin directs text output, specified as an OutputStream instance.

Format of the output fields, specified using formatting operators. formatSpec also can include ordinary text and special characters.

If formatSpec includes literal text representing escape characters, such as \n, then print translates the escape characters.

formatSpec can be a character vector in single quotes, or a string scalar.

Formatting Operator

A formatting operator starts with a percent sign, %, and ends with a conversion character. The conversion character is required. Optionally, you can specify identifier, flags, field width, precision, and subtype operators between % and the conversion character. (Spaces are invalid between operators and are shown here only for readability).

Schematic of formatting operator characters.

Conversion Character

This table shows conversion characters to format numeric and character data as text.

Value TypeConversionDetails

Integer, signed

%d or %i

Base 10

Integer, unsigned

%u

Base 10

%o

Base 8 (octal)

%x

Base 16 (hexadecimal), lowercase letters af

%X

Same as %x, uppercase letters AF

Floating-point number

%f

Fixed-point notation (Use a precision operator to specify the number of digits after the decimal point.)

%e

Exponential notation, such as 3.141593e+00 (Use a precision operator to specify the number of digits after the decimal point.)

%E

Same as %e, but uppercase, such as 3.141593E+00 (Use a precision operator to specify the number of digits after the decimal point.)

%g

The more compact of %e or %f, with no trailing zeros (Use a precision operator to specify the number of significant digits.)

%G

The more compact of %E or %f, with no trailing zeros (Use a precision operator to specify the number of significant digits.)

Characters or strings

%c

Single character

%s

Character vector or string array. The type of the output text is the same as the type of formatSpec.

Optional Operators

The optional identifier, flags, field width, precision, and subtype operators further define the format of the output text.

  • Identifier

    Order for processing the function input arguments. Use the syntax n$, where n represents the positions of the other input arguments in the function call.

    Example: ('%3$s %2$s %1$s %2$s','A','B','C') prints input arguments 'A', 'B', 'C' as follows: C B A B.

    Note: If an input argument is an array, you cannot use identifiers to specify particular array elements from that input argument.

  • Flags

    '–'

    Left-justify.
    Example: %-5.2f
    Example: %-10s

    '+'

    Always print a sign character (+ or –) for any numeric value.
    Example: %+5.2f
    Right-justify text.
    Example: %+10s

    ' '

    Insert a space before the value.
    Example: % 5.2f

    '0'

    Pad to field width with zeros before the value.
    Example: %05.2f

    '#'

    Modify selected numeric conversions:

    • For %o, %x, or %X, print 0, 0x, or 0X prefix.

    • For %f, %e, or %E, print decimal point even when precision is 0.

    • For %g or %G, do not remove trailing zeros or decimal point.

    Example: %#5.0f

  • Field Width

    Minimum number of characters to print. The field width operator can be a number, or an asterisk (*) to refer to an input argument.

    When you specify * as the field width operator, the other input arguments must provide both a width and a value to be printed. Widths and values can be pairs of arguments or pairs within a numeric array. With * as the field width operator, you can print different values with different widths.

    Example: The input arguments ('%12d',intmax) are equivalent to ('%*d',12,intmax).

    Example: The input arguments ('%*d',[2 10 5 100]) return '10 100', with two spaces allocated for 10 and five spaces for 100. As an alternative, you also can specify the field widths and values as multiple arguments, as in ('%*d',2,10,5,100).

    The function pads to field width with spaces before the value unless otherwise specified by flags.

  • Precision

    For %f, %e, or %E

    Number of digits to the right of the decimal point
    Example: '%.4f' prints pi as '3.1416'

    For %g or %G

    Number of significant digits
    Example: '%.4g' prints pi as '3.142'

    The precision operator can be a number, or an asterisk (*) to refer to an argument.

    When you specify * as the field precision operator, the other input arguments must provide both a precision and a value to be printed. Precisions and values can be pairs of arguments, or pairs within a numeric array. With * as the precision operator, you can print different values to different precisions.

    When you specify *.* as field width and precision operators, you must specify field widths, precisions, and values as triplets.

    Example: The input arguments ('%.4f',pi) are equivalent to ('%.*f',4,pi).

    Example: The input arguments ('%6.4f',pi) are equivalent to ('%*.*f',6,4,pi).

    Example: The input arguments ('%*.*f',6,4,pi,9,6,exp(1)) return '3.1416 2.718282', with 9 and 6 as the field width and precision for the output of exp(1).

    Note

    If you specify a precision operator for floating-point values that exceeds the precision of the input numeric data type, the results might not match the input values to the precision you specified. The result depends on your computer hardware and operating system.

  • Subtypes

    You can use a subtype operator to print a floating-point value as its octal, decimal, or hexadecimal value. The subtype operator immediately precedes the conversion character. This table shows the conversions that can use subtypes.

    Input Value Type

    Subtype and Conversion Character

    Output Value Type

    Floating-point number

    %bx or %bX
    %bo
    %bu

    Double-precision hexadecimal, octal, or decimal value
    Example: %bx prints pi as 400921fb54442d18

    %tx or %tX
    %to
    %tu

    Single-precision hexadecimal, octal, or decimal value
    Example: %tx prints pi as 40490fdb

Text Before or After Formatting Operators

formatSpec can also include additional text before a percent sign, %, or after a conversion character. The text can be:

  • Ordinary text to print.

  • Special characters that you cannot enter as ordinary text. This table shows how to represent special characters in formatSpec.

    Special Character

    Representation

    Single quotation mark

    ''

    Percent character

    %%

    Backslash

    \\

    Alarm

    \a

    Backspace

    \b

    Form feed

    \f

    New line

    \n

    Carriage return

    \r

    Horizontal tab

    \t

    Vertical tab

    \v

    Character whose Unicode® numeric value can be represented by the hexadecimal number, N

    \xN

    Example: print('\x5A') returns 'Z'

    Character whose Unicode numeric value can be represented by the octal number, N

    \N

    Example: print('\132') returns 'Z'

Notable Behavior of Conversions with Formatting Operators

  • Numeric conversions print only the real component of complex numbers.

  • If you specify a conversion that does not fit the data, such as a text conversion for a numeric value, MATLAB® overrides the specified conversion, and uses %e.

    Example: '%s' converts pi to 3.141593e+00.

  • If you apply a text conversion (either %c or %s) to integer values, MATLAB converts values that correspond to valid character codes to characters.

    Example: '%s' converts [65 66 67] to ABC.

Data to display, specified as numeric, character, or string arrays.

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | logical | char | string

Attributes

Abstracttrue

To learn about attributes of methods, see Method Attributes.

Examples

expand all

In a file in your current folder, create a class named ToFigure that redirects the plugin output to a figure and displays it in a list box within the figure. Define the Figure and ListBox properties to represent the figure and the handle to the list box, respectively.

classdef ToFigure < matlab.automation.streams.OutputStream
    
    properties(SetAccess = private)
        Figure
    end
    properties(Access = private)
        ListBox
    end

You must implement the print method for any subclass of OutputStream. In this example, the method creates a new figure (if necessary), formats the incoming text, and then adds it to the output stream.

    methods
        function print(stream,formatSpec,varargin)
            % Create the figure
            if isempty(stream.Figure) || ~ishghandle(stream.Figure)
                stream.createFigure
            end
            newStr = sprintf(formatSpec,varargin{:});
            oldStr = strjoin(stream.ListBox.String','\n');
            
            % Create the full message
            fullStr = strjoin([oldStr,newStr]);
            fullStrArray = strsplit(fullStr,'\n','CollapseDelimiters',false);
            
            % Set the string and selection
            stream.ListBox.String = fullStrArray';
            stream.ListBox.Value = numel(fullStrArray);
            drawnow
        end
    end

In a methods block with private access, implement a helper method named createFigure that creates the figure and the list box used by the plugin.

    methods(Access = private)
        function createFigure(stream)
            stream.Figure = figure(...
                'Name',         'Unit Test Output',...
                'WindowStyle',  'docked');
            
            stream.ListBox = uicontrol(...
                'Parent',       stream.Figure,...
                'Style',        'listbox',...
                'String',       {},...
                'Units',        'normalized',...
                'Position',     [.05 .05 .9 .9],...
                'Max',          2, ...
                'FontName',     'Monospaced',...
                'FontSize',     13);
        end
    end
end

Save the ToFigure class. Now, in your current folder, create a file named ExampleTest.m containing the following test class. The verifyEqual qualification in testOne causes a test failure. The verification in testTwo passes. The test corresponding to testThree passes without producing an output.

classdef ExampleTest < matlab.unittest.TestCase
    methods(Test)
        function testOne(testCase)  % Test fails
            testCase.verifyEqual(5,4,'Testing 5==4');
        end
        function testTwo(testCase)  % Test passes
            testCase.verifyEqual(5,5,'Testing 5==5');
        end
        function testThree(testCase)
            % test code
        end
    end
end

At the command prompt, create a test suite from the ExampleTest class.

import matlab.unittest.TestRunner
import matlab.unittest.plugins.DiagnosticsValidationPlugin

suite = testsuite('ExampleTest');

Create a test runner that displays output to the command window.

runner = TestRunner.withTextOutput;

Create a DiagnosticsValidationPlugin instance that explicitly specifies that its output should go to a figure using the ToFigure output stream.

plugin = DiagnosticsValidationPlugin(ToFigure);

Add the plugin to the runner and run the tests.

runner.addPlugin(plugin)
result = runner.run(suite);
Running ExampleTest

================================================================================
Verification failed in ExampleTest/testOne.
    ----------------
    Test Diagnostic:
    ----------------
    Testing 5==4
    ---------------------
    Framework Diagnostic:
    ---------------------
    verifyEqual failed.
    --> The numeric values are not equal using "isequaln".
    --> Failure table:
            Actual    Expected    Error    RelativeError
            ______    ________    _____    _____________
                                                        
              5          4          1          0.25     
    
    Actual Value:
         5
    Expected Value:
         4
    ------------------
    Stack Information:
    ------------------
    In C:\work\ExampleTest.m (ExampleTest.testOne) at 4
================================================================================
...
Done ExampleTest
__________

Failure Summary:

     Name                 Failed  Incomplete  Reason(s)
    ==================================================================
     ExampleTest/testOne    X                 Failed by verification.

Only the test failures produce output to the screen. By default, TestRunner.withTextOutput uses a DiagnosticsOutputPlugin to display output on the screen.

In addition to the default text output being displayed on the screen, the DiagnosticsValidationPlugin output is directed to a docked figure. The figure shows this text.

------------------------------
Validation of Test Diagnostic:
------------------------------
Testing 5==4
------------------------------
Validation of Test Diagnostic:
------------------------------
Testing 5==5

The DiagnosticsValidationPlugin displays the diagnostic information regardless of whether the tests encounter failure conditions.

Version History

Introduced in R2014a