Matlab: difference between string array and string

Foreword

When formatting the output with sprintf (), I found that formatSpec can be a string array created with single quotes or a string created with string ('str'). So I was wondering, what is the difference between the two, and where does each apply?

Official documents

Character arrays and string arrays provide storage for text data in MATLAB®.

    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. Starting in R2017a, you can create strings using double quotes, such as str = "Greetings friend". To convert data to string arrays, use the string function.

Code

str=sprintf('pi = %.5f',pi);  %输出类型为char
str1=sprintf(string('pi = %.5f'),pi);    %输出类型为string

Output result:

%测试字符串数组
>> class(str)
ans =
char

>> str(1)
ans =
p

>> size(str)
ans =
     1    12

%测试string
>> class(str1)
ans =
string

>> size(str1)
ans =
     1     1
     
>> str1(1)
ans = 
  string
    "pi = 3.14159"

to sum up

It can be seen from the documentation:

  1. A string array is equivalent to a matrix (vector) of data type char. Created with single quotes. Can be indexed.
  2. string is equivalent to a class. Use the string () function to create an instance object. So there are functions that can operate on strings. The size is 1 * 1.
Published 47 original articles · Like 33 · Visit 310,000+

Guess you like

Origin blog.csdn.net/kaever/article/details/70207486