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 characters.
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. To control the display of block names, on the Format tab, select Auto > Hide Automatic Block Names. 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:
Action | Block |
---|---|
Convert a uint8 vector to a string signal. | |
Compose an output string signal based on the Format parameter and input signals. | |
Scan an input string and convert it to signals per the format specified by Format parameter. | |
Compare two input strings. | |
Concatenate input strings to form one output string. | |
Output the string specified by the String parameter. | |
Return the index of the first occurrence of the pattern string sub in the text string str. | |
Output the number of characters in the input string. | |
Convert a string signal to a uint8 vector. | |
Convert string signal to double signal. | |
Convert string signal to single signal. | |
Convert an input string to an enumerated signal. | |
Extract a substring from a string signal. | |
Convert the input signal to a string signal. |
These Simulink blocks support strings.
Block | Notes |
---|---|
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 |
In Bus Element | Including root level. |
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. |
MATLAB Function | — |
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. |
Out Bus Element | Including root level. |
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 | — |
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
, enterstringtype(100)
. You can also use thestringtype
function on the MATLAB command line to create a string data type.Starting in R2024a, symbolic expression is supported for maximum length of string data types. For more information about symbolic dimensions, see Implement Symbolic Dimensions for Array Sizes in Generated Code (Simulink Coder).
However, the following limitations apply for string data types that use symbolic expression as maximum length.
Stateflow blocks, MATLAB Function block, and MATLAB System block do not support string data types that use symbolic expression as maximum length.
Blocks with constant sample time, such as String Constant block, do not support string data types with symbolic dimension as maximum length.
Use the
set_param
function with theOutDataTypeStr
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 characters, 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 Simulink.Bus
object to accept strings
using the Type Editor, for the DataType parameter of the Simulink.BusElement
object, 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
. You can create mixed use numeric and
string objects for bus elements. For more information on creating Bus
and
BusElement
objects with the Type Editor, see Type Editor.
Strings and Generated Code
Consider these notes for strings and generated C
and
C++
code.
Differences Between Simulation and Generated C
Code for the Dynamic String Data Type
Simulation of blocks that use a dynamic string data type differ from generated
C
code in these ways:
Signals with
string
data type have dynamic sizes during simulation. In other words, the size of a string can vary between 0 and 32766. However, in generatedC
code, the coder stores strings as fixed-sizechar_T
arrays. Therefore, the size of a string is limited by a fixed buffer size in generatedC
code. The software truncates extra characters and inserts a null terminator at the end (for example, at the output of a String Concatenate block).The coder generates string invariants (parameters or signals) as
C
-style double-quoted strings.The default buffer size for a signal with string data type is 256 bytes (contains at most 255 8-bit ASCII characters). To change this buffer size, use the Buffer size of dynamically-sized string (bytes) (Simulink Coder) configuration parameter.
To override a model-wide setting for an individual string signal, use
stringtype(N)
as the signal data type. Signals with this data type are allocated a buffer ofN+1
bytes in generatedC
code (N characters plus one null terminator).There is no difference between simulation and generated
C++
code when strings are stored asstd::string
objects that have the same dynamic behavior as simulation.
C++
Code Generation String Library
For C++
code generation, std::string
library
is available for an ERT-based target with an Embedded Coder™
license. For more information, see Generate Code for String Blocks by Using the Standard C++ String Library (Embedded Coder).
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 Convert | Block |
---|---|
String signal to uint8 vector signal while preserving ASCII characters | |
Uint8 vector signal to string signal | |
String signal to numerical signal double data type | |
String signal to numerical signal single data type | |
String signal to enumerated signal data type | |
Input signal to string signal |
Convert String to ASCII and Back to String
Add these blocks to a model:
String Constant
String to ASCII
ASCII to String
Two Display blocks
Connect the blocks as shown.
In the String Constant block, enter a string, such as
"Hello!"
.In the String to ASCII block, change the maximum string size to 10.
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 ofH
and33
is the ASCII equivalent of!
.Display1 has filled the remaining space to the maximum string length of 10 with zeros (null characters).
Display shows
Hello!
after the ASCII to String block reconverts the ASCII code to a string.
Convert String to Enumerated Data Type
Add these blocks to a model:
String Constant
String to Enum
Display
Connect the blocks as shown.
In the String Constant block, enter a string, such as
"Hello!"
Create a Simulink enumeration class named
BasicStrings
and store it in the current folder with the file nameBasicStrings.m
, for example:classdef BasicStrings < Simulink.IntEnumType enumeration Hello(0) Red(1) Blue(2) end end
In the String to Enum block, enter the enumeration class as
Enum: BasicStrings
.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.
Add these blocks to a model:
Six Constant
One Compose String
One Scan String
Seven Display
Change the Constant block constant values to those shown and connect the blocks.
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 (
"
).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.
Add these blocks to a model:
Two String Constant
String Find
One Display
Connect the blocks as shown.
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.
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.
Simulate the model and observe the contents of the Display block. For this example, the block displays
7
, which is the location of the letterG
.
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.
Add a Substring block to the model.
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.
Connect the new block as shown.
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 Model Fault-Tolerant Fuel Control System example model
sldemo_fuelsys
enumerates constants in multiple areas to work
with textual data.
In sldemo_fuelsys/fuel_rate_control/control_logic
, 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 the 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:
Category | Limitation Description | Workaround |
---|---|---|
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. |
MATLAB S-Function | Custom blocks created with this block 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. |
| The | — |
| The
| — |
Data Type Conversion block | Do not use the Data Type Conversion block to convert to or from strings. | Use the string conversion blocks |
To File block | Load strings using the To File block. | — |
Scope and Spectrum Analyzer blocks, Logic Analyzer app | The Scope and Spectrum Analyzer blocks and the Logic Analyzer app do not display strings. | Use the Display, the Simulation Data Inspector, or the Sequence Viewer in Stateflow. |
See Also
Blocks
- Compose String | Scan String | String Compare | String Concatenate | String Constant | String Find | String Length | String to Double | String to Single | String to Enum | String to ASCII | Substring | To String