Create String Arrays - MATLAB & Simulink (2024)

Open Live Script

String arrays store pieces of text and provide a set of functions for working with text as data. You can index into, reshape, and concatenate strings arrays just as you can with arrays of any other type. You also can access the characters in a string and append text to strings using the plus operator. To rearrange strings within a string array, use functions such as split, join, and sort.

Create String Arrays from Variables

MATLAB® provides string arrays to store pieces of text. Each element of a string array contains a 1-by-n sequence of characters.

You can create a string using double quotes.

str = "Hello, world"
str = "Hello, world"

As an alternative, you can convert a character vector to a string using the string function. chr is a 1-by-17 character vector. str is a 1-by-1 string that has the same text as the character vector.

chr = 'Greetings, friend'
chr = 'Greetings, friend'
str = string(chr)
str = "Greetings, friend"

Create a string array containing multiple strings using the [] operator. str is a 2-by-3 string array that contains six strings.

str = ["Mercury","Gemini","Apollo"; "Skylab","Skylab B","ISS"]
str = 2x3 string "Mercury" "Gemini" "Apollo" "Skylab" "Skylab B" "ISS" 

Find the length of each string in str with the strlength function. Use strlength, not length, to determine the number of characters in strings.

L = strlength(str)
L = 2×3 7 6 6 6 8 3

As an alternative, you can convert a cell array of character vectors to a string array using the string function. MATLAB displays strings in string arrays with double quotes, and displays characters vectors in cell arrays with single quotes.

C = {'Mercury','Venus','Earth'}
C = 1x3 cell {'Mercury'} {'Venus'} {'Earth'}
str = string(C)
str = 1x3 string "Mercury" "Venus" "Earth"

In addition to character vectors, you can convert numeric, datetime, duration, and categorical values to strings using the string function.

Convert a numeric array to a string array.

X = [5 10 20 3.1416];string(X)

Convert a datetime value to a string.

d = datetime('now');string(d)
ans = "12-Feb-2024 23:24:55"

Also, you can read text from files into string arrays using the readtable, textscan, and fscanf functions.

Create Empty and Missing Strings

String arrays can contain both empty and missing values. An empty string contains zero characters. When you display an empty string, the result is a pair of double quotes with nothing between them (""). The missing string is the string equivalent to NaN for numeric arrays. It indicates where a string array has missing values. When you display a missing string, the result is <missing>, with no quotation marks.

Create an empty string array using the strings function. When you call strings with no arguments, it returns an empty string. Note that the size of str is 1-by-1, not 0-by-0. However, str contains zero characters.

str = strings
str = ""

Create an empty character vector using single quotes. Note that the size of chr is 0-by-0.

chr = ''
chr = 0x0 empty char array

Create a string array where every element is an empty string. You can preallocate a string array with the strings function.

str = strings(2,3)
str = 2x3 string "" "" "" "" "" ""

To create a missing string, convert a missing value using the string function. The missing string displays as <missing>.

str = string(missing)
str = <missing>

You can create a string array with both empty and missing strings. Use the ismissing function to determine which elements are strings with missing values. Note that the empty string is not a missing string.

str(1) = "";str(2) = "Gemini";str(3) = string(missing)
str = 1x3 string "" "Gemini" <missing>
ismissing(str)
ans = 1x3 logical array 0 0 1

Compare a missing string to another string. The result is always 0 (false), even when you compare a missing string to another missing string.

str = string(missing);str == "Gemini"
ans = logical 0
str == string(missing)

Access Elements of String Array

String arrays support array operations such as indexing and reshaping. Use array indexing to access the first row of str and all the columns.

str = ["Mercury","Gemini","Apollo"; "Skylab","Skylab B","ISS"];str(1,:)
ans = 1x3 string "Mercury" "Gemini" "Apollo"

Access the second element in the second row of str.

str(2,2)
ans = "Skylab B"

Assign a new string outside the bounds of str. MATLAB expands the array and fills unallocated elements with missing values.

str(3,4) = "Mir"
str = 3x4 string "Mercury" "Gemini" "Apollo" <missing> "Skylab" "Skylab B" "ISS" <missing> <missing> <missing> <missing> "Mir" 

Access Characters Within Strings

You can index into a string array using curly braces, {}, to access characters directly. Use curly braces when you need to access and modify characters within a string element. Indexing with curly braces provides compatibility for code that could work with either string arrays or cell arrays of character vectors. But whenever possible, use string functions to work with the characters in strings.

Access the second element in the second row with curly braces. chr is a character vector, not a string.

str = ["Mercury","Gemini","Apollo"; "Skylab","Skylab B","ISS"];chr = str{2,2}
chr = 'Skylab B'

Access the character vector and return the first three characters.

str{2,2}(1:3)
ans = 'Sky'

Find the space characters in a string and replace them with dashes. Use the isspace function to inspect individual characters within the string. isspace returns a logical vector that contains a true value wherever there is a space character. Finally, display the modified string element, str(2,2).

TF = isspace(str{2,2})
TF = 1x8 logical array 0 0 0 0 0 0 1 0
str{2,2}(TF) = "-";str(2,2)
ans = "Skylab-B"

Note that in this case, you can also replace spaces using the replace function, without resorting to curly brace indexing.

replace(str(2,2)," ","-")
ans = "Skylab-B"

Concatenate Strings into String Array

Concatenate strings into a string array just as you would concatenate arrays of any other kind.

Concatenate two string arrays using square brackets, [].

str1 = ["Mercury","Gemini","Apollo"];str2 = ["Skylab","Skylab B","ISS"];str = [str1 str2]
str = 1x6 string "Mercury" "Gemini" "Apollo" "Skylab" "Skylab B" "ISS"

Transpose str1 and str2. Concatenate them and then vertically concatenate column headings onto the string array. When you concatenate character vectors into a string array, the character vectors are automatically converted to strings.

str1 = str1';str2 = str2';str = [str1 str2];str = [["Mission:","Station:"] ; str]
str = 4x2 string "Mission:" "Station:" "Mercury" "Skylab" "Gemini" "Skylab B" "Apollo" "ISS" 

Append Text to Strings

To append text to strings, use the plus operator, +. The plus operator appends text to strings but does not change the size of a string array.

Append a last name to an array of names. If you append a character vector to strings, then the character vector is automatically converted to a string.

names = ["Mary";"John";"Elizabeth";"Paul";"Ann"];names = names + ' Smith'
names = 5x1 string "Mary Smith" "John Smith" "Elizabeth Smith" "Paul Smith" "Ann Smith"

Append different last names. You can append text to a string array from a string array or from a cell array of character vectors. When you add nonscalar arrays, they must be the same size.

names = ["Mary";"John";"Elizabeth";"Paul";"Ann"];lastnames = ["Jones";"Adams";"Young";"Burns";"Spencer"];names = names + " " + lastnames
names = 5x1 string "Mary Jones" "John Adams" "Elizabeth Young" "Paul Burns" "Ann Spencer"

Append a missing string. When you append a missing string with the plus operator, the output is a missing string.

str1 = "Jones";str2 = string(missing);str1 + str2
ans = <missing>

Split, Join, and Sort String Array

MATLAB provides a rich set of functions to work with string arrays. For example, you can use the split, join, and sort functions to rearrange the string array names so that the names are in alphabetical order by last name.

Split names on the space characters. Splitting changes names from a 5-by-1 string array to a 5-by-2 array.

names = ["Mary Jones";"John Adams";"Elizabeth Young";"Paul Burns";"Ann Spencer"];names = split(names)
names = 5x2 string "Mary" "Jones" "John" "Adams" "Elizabeth" "Young" "Paul" "Burns" "Ann" "Spencer"

Switch the columns of names so that the last names are in the first column. Add a comma after each last name.

names = [names(:,2) names(:,1)];names(:,1) = names(:,1) + ','
names = 5x2 string "Jones," "Mary" "Adams," "John" "Young," "Elizabeth" "Burns," "Paul" "Spencer," "Ann" 

Join the last and first names. The join function places a space character between the strings it joins. After the join, names is a 5-by-1 string array.

names = join(names)
names = 5x1 string "Jones, Mary" "Adams, John" "Young, Elizabeth" "Burns, Paul" "Spencer, Ann"

Sort the elements of names so that they are in alphabetical order.

names = sort(names)
names = 5x1 string "Adams, John" "Burns, Paul" "Jones, Mary" "Spencer, Ann" "Young, Elizabeth"

See Also

string | strings | strlength | ismissing | isspace | plus | split | join | sort

Related Topics

  • Analyze Text Data with String Arrays
  • Search and Replace Text
  • Compare Text
  • Test for Empty Strings and Missing Values
  • Frequently Asked Questions About String Arrays
  • Update Your Code to Accept Strings
Create String Arrays
- MATLAB & Simulink (2024)

FAQs

How to create string arrays in MATLAB? ›

Creation. You can create a string scalar by enclosing a piece of text in double quotes. To create a string array, you can concatenate string scalars using square brackets, just as you can concatenate numbers into a numeric array.

How do you create a string in Simulink? ›

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.

How to create an array of strings? ›

The String Array is initialized at the same time as it is declared. You can also initialize the String Array as follows: String[] strArray = new String[3]; strArray[0] = “one”; strArray[1] = “two”; strArray[2] = “three”; Here the String Array is declared first.

How to convert string to array in MATLAB? ›

X = str2num( txt ) converts a character array or string scalar to a numeric matrix. The input can include spaces, commas, and semicolons to indicate separate elements. If str2num cannot parse the input as numeric values, then it returns an empty matrix.

How to create an array in MATLAB? ›

To create an array with four elements in a single row, separate the elements with either a comma ( , ) or a space. This type of array is a row vector. To create a matrix that has multiple rows, separate the rows with semicolons. Another way to create a matrix is to use a function, such as ones , zeros , or rand .

What is the difference between char array and string array? ›

A character array is a sequence of characters, just as a numeric array is a sequence of numbers. A typical use is to store short pieces of text as character vectors, such as c = 'Hello World' . A string array is a container for pieces of text. String arrays provide a set of functions for working with text as data.

How to create a Simulink function? ›

Create Simulink Function Using Exported MATLAB Function from Stateflow Chart. Set up a MATLAB function in a Stateflow chart to receive data through an input argument from a function caller and then pass a calculated value back through an output argument. Set chart parameters to export the function to a Simulink model.

How to store string in array in Matlab? ›

Create String Arrays from Variables

MATLAB® provides string arrays to store pieces of text. Each element of a string array contains a 1-by-n sequence of characters. You can create a string using double quotes. As an alternative, you can convert a character vector to a string using the string function.

Can I turn a string into an array? ›

Declare a string variable str and assign the desired string to it. Use the toCharArray() method on the string str to convert it into an array of characters. This method splits the string into individual characters and returns an array containing those characters.

What is a string array? ›

A String Array is an Array of a fixed number of String values. A String is a sequence of characters. Generally, a string is an immutable object, which means the value of the string can not be changed. The String Array works similarly to other data types of Array. In Array, only a fixed set of elements can be stored.

How to convert string array to cell array in MATLAB? ›

Convert String Array to Cell Array

To pass data from a string array to such functions, use the cellstr function to convert the string array to a cell array of character vectors. Create a string array. You can create strings using double quotes.

How to define string in MATLAB? ›

You can create a string using double quotes. As an alternative, you can convert a character vector to a string using the string function. chr is a 1-by-17 character vector. str is a 1-by-1 string that has the same text as the character vector.

How do you convert a matrix to a string array in MATLAB? ›

str = mat2str( A , n ) converts fi object A to a string representation using n bits of precision. str = mat2str( A , 'class') creates a string representation with the name of the class of A included. This option ensures that the result of evaluating str will also contain the class information.

How do you create an array structure in Matlab? ›

s = struct( field , value ) creates a structure array with the specified field and value. The value input argument can be any data type, such as a numeric, logical, character, or cell array. If value is not a cell array, or if value is a scalar cell array, then s is a scalar structure.

How to make an empty array of strings in Matlab? ›

For example, str = "" creates a string scalar that contains no characters. str = strings( n ) returns an n -by- n string array. Each element is a string with no characters.

Top Articles
Latest Posts
Article information

Author: Aracelis Kilback

Last Updated:

Views: 6243

Rating: 4.3 / 5 (44 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Aracelis Kilback

Birthday: 1994-11-22

Address: Apt. 895 30151 Green Plain, Lake Mariela, RI 98141

Phone: +5992291857476

Job: Legal Officer

Hobby: LARPing, role-playing games, Slacklining, Reading, Inline skating, Brazilian jiu-jitsu, Dance

Introduction: My name is Aracelis Kilback, I am a nice, gentle, agreeable, joyous, attractive, combative, gifted person who loves writing and wants to share my knowledge and understanding with you.