Simulink Strings - MATLAB & Simulink (original) (raw)

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"str_N_" (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 theDisplay 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. TheASCII 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:

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 > . 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:

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 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:

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:

For example, using the String Constant block to create a string with the Output data type parameter set tostringtype(31) creates a string data type ofstr31. 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 andBusElement objects with the Type Editor, see Type Editor.

Strings and Generated Code

Consider these notes for strings and generated C andC++ 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 generatedC code in these ways:

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.

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 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

  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 nameBasicStrings.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 asEnum: 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 theString 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 thestr 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:

To see the locations of the characters throughout the model, add oneDisplay 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 modelsldemo_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:

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. Insldemo_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 theConstant 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.

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.
Simulink.Signal The Simulink.Signal object does not support strings.
Simulink.Parameter The Simulink.Parameter object supports strings with these limitations:Simulink.Parameter objects with string data types support only these Simulink Coder™ storage classes: Auto,Default, Model Default, ExportedGlobal, and ImportedExtern, ImportedExternPointerSimulink.Parameter objects with string data types do not support expressions generated by theslexpr function.
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.
Initial value or initial condition parameter Initial value or initial condition parameters for blocks such as Delay and Data Store Memory do not accept string values. Configure initial value or condition to the default value ('0').

See Also

Blocks

Functions

Topics