Simulink Strings

Use strings in multiple applications when you want to pass and manipulate text. For example, when modeling a fuel control system, instead of using enumerated data to model the fuel levels, you can use strings like "LOW" or "EMPTY". Simulink® strings are compatible with MATLAB® strings.

Simulink strings are a built-in signal data type. They appear in the Simulink Editor as "strN" (for example, string with maximum length of N characters) or "string" for strings without maximum length (dynamic strings). String lengths can range from 1 to 32,766.

Simulink string signals are inherently discrete. If your string signal has a continuous sample time, the model generates an error at compilation time.

Simulink treats string variables and expressions, such as "a" + "b", the same way it treats numeric variables. The value of a string variable can be both a character vector and a MATLAB string. String variables can exist in base, model, and mask workspaces.

String literals are specified with double quotes ("Hello") or single quotes ('Hello'). To be consistent with MATLAB strings, use double quotes. Strings appear on ports and in the Display block with double quotes.

Simulink strings support 256 characters of the ISO/IEC 8859-1 character set. These characters are the first 256 code points of Unicode. Simulink does not support the first character char(0) ("NULL") and returns an error if the string contains this character.

When a character cannot be displayed, the block stores the actual information and outputs an escape character with the associated octal value for the character. For example, the decimal value control character for BREAK PERMITTED HERE is 130. The block displays this control character as the escaped octal \202. The ASCII to String block returns as escaped octals characters in the Unicode set range 0000 to 001F and 007F-009F.

This topic describes how to use strings in Simulink, including:

  • A list of available string blocks and blocks particular to string conversions

  • Passing string constants into other string blocks

  • Null characters in strings

  • Strings with no maximum length

  • Interactions with Stateflow®

  • Generated code

  • Limitations

This topic also includes simple examples illustrating how to use string blocks. Examples in this topic enable the display of block names with the Display > Hide Automatic Names enabled. For example, you can use string blocks to display and extract coordinate data and find patterns in strings.

To work with strings in your model, use this table:

ActionBlock

Convert a uint8 vector to a string signal.

ASCII to String

Compose an output string signal based on the Format parameter and input signals.

Compose String

Scan an input string and convert it to signals per the format specified by Format parameter.

Scan String

Compare two input strings.

String Compare

Concatenate input strings to form one output string.

String Concatenate

Output the string specified by the String parameter.

String Constant

Return the index of the first occurrence of the pattern string sub in the text string str.

String Find

Output the number of characters in the input string.

String Length

Convert a string signal to a uint8 vector.

String to ASCII

Convert string signal to double signal.

String to Double

Convert string signal to single signal.

String to Single

Convert an input string to an enumerated signal.

String to Enum

Extract a substring from a string signal.

Substring

Convert the input signal to a string signal.

To String

These Simulink blocks support strings.

BlockNotes

Bus Assignment

Nonvirtual and virtual.

Bus Creator

Nonvirtual and virtual.

Bus Selector

Nonvirtual and virtual.

Data Store Memory

Data Store Read

Data Store Write

Data Type Duplicate

Display

Display strings with double quotes.

From

From Workspace

Interpolation of data is not supported.

Goto

Ground

Ground value is "" (empty string).

Inport

Including root level.

Manual Variant Sink

Manual Variant Source

Manual Switch

No mixed numeric and string types. If there are multiple strings, the block uses string with the largest size or the dynamic string.

Merge

Model

Multiport Switch

No mixed numeric and string types. If there are multiple strings, the block uses string with the largest size or the dynamic string.

Outport

Including root level.

Probe

Signal Editor

Interpolation of data is not supported.

Signal Specification

Subsystem (all variations)

Switch

No mixed numeric and string types. If there are multiple strings, the block uses string with the largest size or the dynamic.

Terminate Function

Terminator

Variant Source

Variant Model

Variant Subsystem

Width

Simulink Strings and Stateflow

To use textual data to control chart behavior and manipulate text to create natural language output in Stateflow, use strings in C action language charts. Stateflow provides operators to manipulate strings. For more information, see Manage Textual Information by Using Strings (Stateflow).

String Constants

To specify string constants, use the String Constant block. Do not use the Constant block, which does not accept strings. In the String Constant block, enter the string with double quotes, such as "Hello!" in the String parameter. It is the same as adding a numeric constant in the Constant value parameter of the Constant block.

Simulink Strings and Null Characters

Simulink strings automatically deal with string termination. Do not use a null terminator at the end of a string. If Simulink detects a null character anywhere in a string, it generates an error. Simulink handles strings during simulation and code generation as follows:

  • During simulation, the model simulates. You do not need to do anything else.

  • During C code generation, the software adds a null terminator to the end of the string. For example, if the string buffer size is 10 and the real string value is "AB", the third character in the generated code is a null terminator.

String Data Type

As necessary, string blocks create and use string data types, for example, when a block outputs a string type. You can create strings without specifying a maximum length of characters. We refer to strings without a maximum length of characters as dynamic strings.

To create string data types for blocks that support strings, you can:

  • Use the Output data type or Data type parameter on the Signal Attributes tab of a Simulink block.

    • To create a string data type with no maximum length of characters, specify string. This action creates a dynamic string.

    • To create a string data type with maximum length of characters, such as 100, enter stringtype(100). You can also use the stringtype function on the MATLAB command line to create a string data type.

  • Use the set_param function with the OutDataTypeStr parameter, for example:

    set_param(gcb,'OutDataTypeStr','stringtype(100)')

    This function creates a string data type object with a maximum length of 100 characters. String type lengths can range from 1 to 32,766 , inclusive.

For example, using the String Constant block to create a string with the Output data type parameter set to stringtype(31) creates a string data type of str31. 31 is the maximum number of characters the string can have.

Strings in Bus Objects

To configure an element of a bus object to accept strings using the Bus Editor, in the DataType parameter of the bus element, enter a string type. For example, to specify a string data type whose maximum length of characters is 10, enter stringtype(10). The Mode parameter updates accordingly. To specify a dynamic signal with a variable length, enter string in this field. You can create mixed use numeric and string bus objects for bus elements. For more information on creating bus objects and elements with the Bus Editor, see Create Bus Objects with the Bus Editor.

Strings and Generated Code

During code generation, the software adds a null terminator to the end of the string. For example, if the string buffer size is 10 and the real string value is AB, the third character in the generated code is a null terminator. In generated code:

  • Strings are represented as fixed-size char_T arrays.

  • String invariants (parameters or signals) are generated as C-style double-quoted strings.

String Data Type Conversions

You cannot use the Data Type Conversion block to convert string data types to other data types and conversely. Instead, use these string conversion blocks.

To ConvertBlock

String signal to uint8 vector signal while preserving ASCII characters

String To ASCII

Uint8 vector signal to string signal

ASCII to String

String signal to numerical signal double data type

String to Double

String signal to numerical signal single data type

String to Single

String signal to enumerated signal data type

String To Enum

Input signal to string signal

To String

Convert String to ASCII and Back to String

  1. Add these blocks to a model:

    • String Constant

    • String to ASCII

    • ASCII to String

    • Two Display blocks

  2. Connect the blocks as shown.

  3. In the String Constant block, enter a string, such as "Hello!".

  4. In the String to ASCII block, change the maximum string size to 10.

  5. Simulate the model and observe the contents of the Display blocks.

    • Display1 shows Hello! converted to its ASCII equivalent. For example, 72 is the ASCII equivalent of H and 33 is the ASCII equivalent of !.

    • Display1 has filled the remaining space to the maximum string length of 10 with zeroes (null characters).

    • Display shows Hello! after the ASCII to String block reconverts the ASCII code to a string.

Convert String to Enumerated Data Type

  1. Add these blocks to a model:

    • String Constant

    • String to Enum

    • Display

  2. Connect the blocks as shown.

  3. In the String Constant block, enter a string, such as "Hello!"

  4. Create a Simulink enumeration class named BasicStrings and store it in the current folder with the file name BasicStrings.m, for example:

    classdef BasicStrings < Simulink.IntEnumType
    enumeration
        Hello(0)
        Red(1)
        Blue(2) 
        end
    end 
  5. In the String to Enum block, enter the enumeration class as Enum: BasicStrings.

  6. Simulate the model and observe the contents of the Display block.

Display and Extract Coordinate Data

This example shows how you can format and output a set of data as geographic coordinates using the Compose String and Scan String blocks. Based on the C scanf and printf functions, the Compose String and Scan String blocks are similar in concept to the sprintf and sscanf functions, with the primary exception being that those functions work with arrays, which the blocks do not. For more information on string block formatted characters, see Compose String and Scan String.

The Compose String block constructs a string from multiple string and numerical inputs combined. Use the Format parameter to format the output of each input, one format operator for each input. Each format operator starts with a percent sign, %, followed by the conversion character, for example, %f generates fixed point output. To supplement the string output, you can also add extra characters to the format specification to appear in the output.

  1. Add these blocks to a model:

    • Six Constant

    • One Compose String

    • One Scan String

    • Seven Display

  2. Change the Constant block constant values to those shown and connect the blocks.

  3. In the Format parameter for the Compose String blocks, enter these format specifications:

    '%g° %g'' %f" N, %g° %g'' %f" W'
    • The %g and %f formatting operators convert numeric inputs to floating point values. %g is a more compact version of %f.

    • The degree symbol (°), N, W, and ' are supplemental strings to display in the output string.

    The Compose String block combines the output in the input order, formats each input according to its format operator, adds the extra strings, and outputs the string, formatted as directed and surrounded by double quotes (").

  4. In the Format parameter for the Scan String block, enter these format specifications:

    '%g° %g'' %f" N, %g° %g'' %f" W'
    • The %g and %f formatting operators convert numeric inputs to floating point values. %g is a more compact version of %f.

    • The degree symbol (°), N, W, and ' are supplemental strings to display in the output string.

    The Scan String block reads its input, converts it according to the format specified by a conversion specification, and returns the results as scalars. The block formats each output according to its conversion specification. It ignores specified text immediately before or after a conversion specifier.

Find Patterns in Strings

To find a pattern in a string, use the String Find block.

  1. Add these blocks to a model:

    • Two String Constant

    • String Find

    • One Display

  2. Connect the blocks as shown.

  3. In the first String Constant block, enter a string, such as "Hello!Goodbye!".

    Connecting this block to the str input port of the String Find block causes the String Find block to look for the pattern in this string.

  4. In the second String Constant block, enter a string (or pattern) to look for in the first String Constant string, such as "Goodbye!".

    Connecting this block to the sub input port of the block means that the String Find looks for this pattern from the str input.

  5. Simulate the model and observe the contents of the Display block. For this example, the block displays 7, which is the location of the letter G.

Extract a String

To extract a string from a source string, use the Substring block. This example uses the model described in Find Patterns in Strings.

  1. Add a Substring block to the model.

  2. In the Substring block, select the Output string from 'idx' to end parameter. Setting this parameter extracts the string from the location input at the idx port to the end of the string.

  3. Connect the new block as shown.

  4. Simulate the model and observe the contents of the Display block. For this example, the block displays "Goodbye!", which is the substring extracted starting idx to the end of the string.

Get Text Following a Keyword

This example shows basic string manipulation using the Simulink string blocks.

For a model that looks like the following, simulate it.

Observe that the model:

  • Creates two strings, "beginning middle end" and "middle", using String Constant blocks.

  • Looks for the first occurrence of "middle" (idx) and adds the location of the first letter (11) to the length of "middle" (7). It uses the String Find and String Length blocks.

  • Extracts from "beginning middle end" the substring that starts from the end of "middle" (idx+string length = 18), which is the string "end". It uses the Substring block.

  • Compares the calculated value of "end" with the actual string "end" , which returns the Boolean value "1". It uses the String Constant and String Compare blocks.

  • Converts the Boolean value "1" to its string equivalent, "true". It uses the To String block.

To see the locations of the characters throughout the model, add one Display block each to the output of the String Find and String Length blocks and simulate it.

Change Existing Models to Use Strings

In addition to using strings in new models, you can update existing models to use strings. Using strings can simplify the model and make it easier to understand.

For example, in older models, you may have used enumerated data types to represent or pass text in your model. The sldemo_fuelsys example enumerated constants in multiple areas to work with textual data.

In sldemo_fuelsys/fuel_rate_control/airflow_calc, the Stateflow chart uses enumerated data to indicate fuel levels.

In sldemo_fuelsys/fuel_rate_control/airflow_calc, to detect if the fuel is low, the model uses Enumerated Constant and Relational Operator blocks.

Instead, you can use the String Constant and String Compare blocks by setting:

  • The String Constant String parameter to LOW.

  • Using the String Compare block to detect if LOW is coming from another part of the model.

Instead of removing all instances of enumerated constants, you can use strings in conjunction with enumerated constants. Doing so allows you to incrementally migrate your model to use strings. In sldemo_fuelsys/fuel_rate_control/fuel_calc/feedforward_fuel_rate, the Multiport Switch block accepts four enumerated data inputs.

If the fuel_mode port is outputting a string, you can convert that string to an enumerated data type to work with the output from the Constant blocks in this model.

Parse NMEA GPS Text Message

This example shows how to parse text messages in NMEA GPS format using Simulink® string blocks.

Overview

This model shows how to use string data type and blocks provided by Simulink® to read input text messages and extract numeric and text data.

Read message header and convert to enumeration

Simulink® provides the String To Enum block to convert a string to the corresponding enumeration value. In this model, header string "RMB" is converted to NMEASentence.RMB.

Parse text message using Scan String block

One way to parse a text message is to use the Scan String block. It works like sscanf function in C and MATLAB®.

Parse text message with fixed field width

When a text message has fixed width for each data field, Simulink® provides blocks to split the string by index. After the strings have been split, each field can be handled separately.

Simulink String Limitations

These capabilities are currently not supported:

CategoryLimitation DescriptionWorkaround

String array

String arrays are not supported.

Use strings only as scalars.

Unicode characters

Simulink strings do not support the entire Unicode set.

Simulink strings support 256 characters of the ISO/IEC 8859-1 character set (Basic Latin and Latin-1 supplement). These characters are the first 256 code points of Unicode.

Rapid accelerator and external modes

Rapid accelerator and external mode simulation do not support Simulink strings.

Use another mode, such as accelerator mode.

MATLAB Function, MATLAB System, MATLAB S-Function, Stateflow MATLAB chart

Custom blocks created with these blocks do not support strings.

Constant, Initial Condition

These blocks do not work with strings.

Use String Constant block.

Control input of the Switch, Multiport Switch, Switch Case, and If blocks

The control input of the Switch block does not accept strings.

Use the data inputs of these blocks.

Simulink.Signal, Simulink.Parameter

The Simulink.Signal and Simulink.Parameter blocks do not support strings.

Data Type Conversion block

Do not use the Data Type Conversion block to convert to or from strings.

Use the string conversion blocks

Logging of nonvirtual buses that contain string elements

If a nonvirtual bus contains a string element, the entire virtual bus cannot be logged. You can still log the nonstring elements.

 

To Workspace block

Load strings using To Workspace.

Log using output port.

To File block

Load strings using To File.

Scope and Spectrum Analyzer blocks, Logic Analyzer tool

The Scope and Spectrum Analyzer blocks and the Logic Analyzer tool do not display strings.

Use the Display, the Simulation Data Inspector, or the Sequence Viewer in Stateflow.

S-functions

S-functions do not support the string data type.

See Also

| | | | | | | | | | | | |

Related Topics