Lecture 5
Lecture 5
Programming in MATLAB
Lecture-5: Strings and String Arrays
Characters and Strings
str =
str = "Hello, world"
"Hello, world"
str(2,2)
ans =
"Skylab B"
Split String and Find Unique Words
• To find the unique words in a string, split it on space characters and call the unique
function.
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.
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 =
["Mercury","Gemini","Apollo";
"Skylab","Skylab B","ISS"];
chr = str{2,2}
chr =
'Skylab B'
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
str1 = ["Mercury","Gemini","Apollo"];
str2 = ["Skylab","Skylab B","ISS"];
str = [str1 str2]
str = 1x6 string
"Mercury" "Gemini" "Apollo" "Skylab" "Skylab B" "ISS"
Concatenate strings horizontally
Syntax
Concatenate Two Cell Arrays:-
s = strcat(s1,...,sN)
firstnames = {'Abraham’; 'George'};
Examples:-
lastnames = {'Lincoln'; 'Washington'};
s1 = 'Good’;
names = strcat(lastnames, {', '},
s2 = 'morning’; firstnames)
s = strcat(s1,s2) names = 2x1 cell
s= {'Lincoln, Abraham' }
'Goodmorning' {'Washington, George'}
Concatenate arrays vertically
• Syntax
C = vertcat(A,B)
C = vertcat(A1,A2,…,An)
example:-
A1 = ["str1" "str2"];
A2 = ["str3" "str4"];
A3 = ["str5" "str6"];
C = vertcat(A1,A2,A3)
C = 3x2 string
"str1" "str2"
"str3" "str4"
"str5" "str6"
Analyze Text Data with String Arrays
s = fileread('Souvik.txt’)
ans =
‘Souvik Saha’
Assignment-3