MATLAB编程-简介
声明字符串(Declaring Strings)
字符串使用**单引号('
)**声明:
>> fstring = 'hello'
fstring =
hello
如果要在字符串中包含单引号,可以这样做:
>> fstring = ''''
fstring =
'
>> fstring = 'you''re'
fstring =
you're
字符串拼接(Concatenate Strings)
在 MATLAB 中,可以使用中括号 []
将多个字符串拼接(连接为一个整体):
<拼接字符串> = [<字符串1>, <字符串2>, <字符串3>, ...];
以下是一个使用拼接函数构建随机问候语的示例:
>> subject = 'The quick brown fox ' % 句子开头
subject =
'The quick brown fox '
>> verb = 'jumps over '
verb =
'jumps over '
>> object = 'the lazy dog'
object =
'the lazy dog'
>> phrase = [subject, verb, object]
phrase =
'The quick brown fox jumps over the lazy dog'
字符串输入(Inputting Strings)
若要让用户输入字符串,可以使用 input
函数:
>> name = input('Enter your names: ','s')
Enter your names: Matlab_User
name =
'Matlab_User'
字符串处理(String Manipulations)
统计重复词汇(Count Repeating Words)
绕口令示例:
How much wood would a woodchuck chuck
if a woodchuck could chuck wood?
He would chuck, he would, as much as he could,
and chuck as much wood as a woodchuck would
if a woodchuck could chuck wood.
我们想知道单词 “wood” 在该绕口令中出现了多少次,可以使用 count
函数:
>> twister = 'How much wood would a woodchuck chuck if a woodchuck could chuck wood? He would chuck, he would, as much as he could, and chuck as much wood as a woodchuck would if a woodchuck could chuck wood.'
>> count(twister, "wood")
ans =
8
注意:
count
函数会统计字符串中模式的出现次数,因此它也会统计单词 "woodchuck" 中的 "wood"。
大小写敏感统计示例:
phrase = 'The quick brown fox jumps over the lazy dog'
>> count(phrase, 'the')
ans =
1 % 默认大小写敏感,不统计大写的 The
>> count(phrase, 'the', 'IgnoreCase', true)
ans =
2 % 忽略大小写统计
获取字符串长度(Finding Lengths of Strings)
有时你可能需要计算句子中字符的数量,可以使用 length
函数:
>> length(phrase)
ans =
43
从字符串中提取单词(Extracting Words from Strings)
要提取字符串中的某些词,可以使用 字符串名(起始索引:结束索引)
的方式。
注意:空格也被视为一个字符。
字符串索引位置示意(从 1
到 43
):T h e q u i c k b r o
w n f o x j u m p s o v e r t h e l a z y d o g
若要提取 brown fox 和 lazy dog:
>> phrase(11:19)
ans =
'brown fox'
>> phrase(36:43)
ans =
'lazy dog'
字母大小写转换(Lowercase and Uppercase of Strings)
使用 lower
和 upper
函数可以将字符串统一转换为小写或大写:
>> upper(phrase)
ans =
'THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG'
>> lower(phrase)
ans =
'the quick brown fox jumps over the lazy dog'
字符串反转(Reverse Strings)
使用 reverse
或 flip
函数可以将字符串反转:
>> reverse(phrase)
ans =
'god yzal eht revo spmuj xof nworb kciuq ehT'
替换字符串中的字符(Replace Characters in Strings)
若要替换字符串中的某些词语,可以使用 replace
函数。
(该函数的具体用法未在本段中展开,但在 MATLAB 中格式一般如下:)
newStr = replace(originalStr, 'oldWord', 'newWord')
replace
函数的语法如下:
replace(字符串变量, 旧词, 新词)
>> % 我们不想要 brown fox,想替换成 orange fox
>> replace(phrase, 'brown', 'orange')
ans =
'The quick orange fox jumps over the lazy dog'
有时你可能希望一次替换多个词语,这时需要将多个词语声明为单元格数组。但在此之前,请确保旧词和新词的顺序一一对应。
>> % 声明要被替换的旧词
>> old = {'fox','dog'}
old =
1×2 cell array
{'fox'} {'dog'}
>> % 声明对应的新词
>> new = {'cheetah','sloth'}
new =
1×2 cell array
{'cheetah'} {'sloth'}
>> % 按顺序将 fox 和 dog 替换为 cheetah 和 sloth
>> replace(phrase, old, new)
ans =
'The quick brown cheetah jumps over the lazy sloth'
字符串作为字符数组(Character Array)
在 MATLAB 中,字符串本质上是字符数组,如下:
>> fstring = 'hello';
>> class(fstring)
ans =
'char'
由于字符串是数组,所以很多数组操作函数(如 size
、转置 '
等)都适用。同时,字符串也可以使用索引访问具体字符。
对字符数组进行算术运算时,它们会被转换为 double 类型:
>> fstring2 = 'world';
>> fstring + fstring2
ans =
223 212 222 216 211
这些数字是字符对应的 ASCII 值,可通过 double
函数查看:
>> double(fstring)
ans =
104 101 108 108 111
可以使用 char
函数将整数值转换回字符,带小数的会向下取整:
>> char(104)
ans =
'h'
>> char(104.6)
ans =
'h'
特殊字符串函数(Special String Functions)
由于 MATLAB 字符串是字符数组,因此有一些专门处理整段字符串的函数:
-
deblank
:去除字符串末尾的空格。 -
findstr(big, small)
:查找small
是否存在于big
中,返回其起始索引;若找不到则返回空数组[]
。 -
strrep(str1, old, new)
:将str1
中所有old
字符串替换为new
。 -
strcmp(str1, str2)
:用于比较字符串是否完全相等(大小写敏感):
>> string1 = 'a';
>> strcmp(string1, 'a')
ans = 1
>> strcmp(string1, 'A')
ans = 0
>> strcmp(string1, ' a') % 注意前导空格
ans = 0
如果参数为数值数组,即使数值相等,strcmp
也会返回 0:
>> strcmp(1,1)
ans = 0
应使用 ==
来比较数值。
num2str
:将数值转换为字符串
>> % 将 π 保留到小数点后 9 位
>> num2str(pi, '%1.9f')
ans =
'3.141592654'
显示字符串变量值(Displaying String Values)
如果只是想显示字符串,可以省略分号:
>> fstring = 'hello';
>> display([fstring 'world'])
helloworld
MATLAB 不会自动在两个字符串之间插入空格,如需空格需手动添加。
此语法也可用于拼接字符串:
>> fstring = ['you' char(39) 're'] % char(39) 是单引号字符
fstring = you're
strcat
:拼接字符串(适用于单元格数组)
>> strCell = {'A', 'B'};
>> strcat(strCell, '_')
ans =
'A_'
'B_'
注意:strcat
会自动移除多余的空格。
类似 printf
的格式化输出:fprintf
MATLAB 没有 printf
,但可以用 fprintf(1, ...)
实现类似功能,1
表示输出到屏幕:
>> X = 9.2;
>> fprintf(1, '%1.3f\n', X);
9.200
不需要手动调用 num2str
,只需提供格式即可:
>> fprintf(1, 'The value of X is %1.3f meters per second \n', X);
The value of X is 9.200 meters per second
字符串单元格数组(Cell Arrays of Strings)
在读取文本、解析 Excel 文件等操作中,经常会遇到字符串单元格数组。
使用 iscellstr
可判断一个单元格数组是否全部为字符串:
>> notStrCell = {'AA', []};
>> iscellstr(notStrCell)
ans = 0
如若某个元素为空([]
),许多字符串处理函数会报错,因此应提前处理。
搜索字符串单元格数组:
-
strmatch
:查找前缀匹配的字符串,返回索引。使用'exact'
参数可精确匹配:
>> strCell = {'Aa', 'AA'};
>> strmatch('A', strCell)
ans = 1 2
>> strmatch('A', strCell, 'exact')
ans = []
>> strmatch('Aa', strCell, 'exact')
ans = 1
-
strfind
:查找任意位置包含的字符串,返回每个元素中匹配子串的起始索引(以单元格形式返回):
>> strfind(strCell, 'A')
ans =
{ [1] [1 2] }
>> strfind(strCell, 'a')
ans =
{ [2] [] }
结合 cellfun
和 isempty
可进一步筛选:
>> idxCell = strfind(strCell, 'a');
>> isFound = ~cellfun('isempty', idxCell);
>> foundIdx = find(isFound)
foundIdx = 1
-
regexp
:使用正则表达式进行字符串匹配,功能更强大。
MATLAB 实现了部分扩展正则表达式(但不是全部)。更多参考资料:
-
MATLAB 官方文档(说明 MATLAB 支持的语法)
注:MATLAB 原生不支持某些常见字符串操作(如字符串拆分),但很多功能可以通过 Google 搜索找到已有实现。