5. Matlab string variables
› Operations
› Built-in functions
Flow control
› Conditional
› Iterations
Data transport:
› Importing into the workspace
› Exporting from the workspace
5
6. MATLAB also can accept and manipulate string
variables.
A string is defined by enclosing it in single quotes.
Example: aString = ‘Hello World!’
6
7. To convert a
string to
lowercase,
use the lower
command.
Example:
change string
in matrix A to
lowercase:
B = lower(A)
7
8. To convert a
string to
uppercase,
use the upper
command.
Example:
change string
in matrix A to
uppercase:
B = upper(A)
8
10. To replace part of
the string with a
new value, use the
strrep command.
Example: replace
the word ‘lama’
with the word
‘baru’ in the string
str1.
strrep(str1,’lama’,’
baru’)
10
11. Create a vertical
array of strings.
>> C =
strvcat('Hello','Yes','N
o','Goodbye')
>> C =
Hello
Yes
No
Goodbye
11
Detect space characters in
an array
>> isspace(' Find spa ces ')
>> Columns 1 through 13
1 1 0 0 0 0 1
0 0 0 1 0 0
Columns 14 through 15
0 1
12. Use strfind to find a two-letter pattern in string S:
>> S = 'Find the starting indices of the pattern string';
>> strfind(S, 'in')
>> ans =
2 15 19 45
>> strfind(S, 'In')
>> ans =
[]
>> strfind(S, ' ')
>> ans =
5 9 18 26 29 33 41
12
13. Findstr finds a string within another, longer string: k = findstr(str1,str2)
The search performed by findstr is case sensitive. Any leading and
trailing blanks in either input string are explicitly included in the
comparison.
Unlike the strfind function, the order of the input arguments to findstr is
not important. This can be useful if you are not certain which of the two
input strings is the longer one.
>> s = 'Find the starting indices of the shorter string.';
>> findstr(s,'the')
>> ans =
6 30
>> findstr('the',s)
>> ans =
6 30
13
14. Strmatch finds possible matches for a string
The statement
>> x = strmatch('max', strvcat('max', 'minimax',
'maximum'))
returns x = [1; 3] since rows 1 and 3 begin with 'max'.
The statement
>> x = strmatch('max', strvcat('max', 'minimax',
'maximum'),'exact')
returns x = 1, since only row 1 matches 'max' exactly.
14
15. strncmp compares the
first n characters of two
strings
strncmp is case sensitive.
Any leading and trailing
blanks in either of the strings
are explicitly included in the
comparison.
strncmp is intended for
comparison of character
data. When used to
compare numeric data,
strncmp returns 0.
strncmpi compares first
n characters of strings
ignoring case
15
16. strtrim removes leading and trailing white-space
from string
>> str = sprintf(' t Remove leading white-
space')
>> str =
Remove leading white-space
>> str = strtrim(str)
>> str =
Remove leading white-space
16
17. str2num used for String to number conversion
>> str2num('3.14159e0') is approximately .
To convert a string matrix:
>> str2num(['1 2';'3 4'])
>> ans =
1 2
3 4
num2str used for number to string conversion
17
18. int2str used for Integer to string conversion
>> int2str(2+3) is the string '5'.
One way to label a plot is:
>> title(['case number ' int2str(n)])
For matrix or vector inputs, int2str returns a string matrix:
>>int2str(eye(3))
>> ans =
1 0 0
0 1 0
0 0 1
18
19. char(X) can be used to convert an array that
contains positive integers representing numeric
codes into a MATLAB character array.
To print a 3-by-32 display of the printable ASCII
characters:
>> ascii = char(reshape(32:127,32,3)')
>> ascii =
! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ?
@ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ ] ^ _
' a b c d e f g h i j k l m n o p q r s t u v w x y z { | } ~
double(S) converts the string to its equivalent double-
precision numeric codes.
19
20. str=‘012ABCabc’
num=double(str)=[4
8 49 50 65 66 67
97 98 99]
char(num) returns
‘012ABCabc’
Strings also can
undergo arithmetic
operations as they
are dealt by their
ASCII codes
20
21. If…else Operator
The if…else
operator tests a
condition.
If the condition is
true, then execute
the if block.
If the condition is
false, execute the
else block.
21
if (condition)
% if block
else
% else block
end
% conditions that can be tested
% == : is equal to
% ~= : is not equal to
% > : larger than
% >= : larger than or equal
% <= : less than or equal
% < : less than
22. Example:
clear, close all
clc
x = 3;
if (x > 5)
disp('The number is more than 5.')
elseif (x == 5)
disp('The number is equal to 5.')
else
disp('The number is less than 5.')
end
22
23. For loop
Used to repeat a set of statements multiple
times.
The for loop format is:
for(startingvalue:increment:endingvalue)
23
clear, close all
clc
% i is the value of the counter
for i = initial_value:increment:ending_value
% statements in this block will be executed until i
% reaches the ending_value
end
25. While loop
Used to repeat a
set of statements
while the tested
condition is true.
The while loop
format is:
while(condition)
The tested
condition is the
same as if…else
25
% conditions that can be
tested
% == :is equal to
% ~= :is not equal to
% > :larger than
% >= :larger than or equal
% <= :less than or equal
% < :less than
26. Example:
clear, close all
clc
counter = 1;
while(counter <= 15)
st1 = strcat('The value of i inside
the loop is: ',int2str(counter));
disp(st1)
counter = counter + 1;
end
26
27. switch
switch {expression}
case {value1}
{command1; command2; ...}
case {value2}
{command1; command2; ...}
otherwise
{command1; command2; ...}
end
expression evaluation can be to numeric or string
case can be single values or vectors of values
Execution is terminated after first satisfied expression
27
28. File > Import Data % from the navigation bar
>> uiimport <filename>
Example: >> uiimport planetsize.txt
>> dlmread('filename', '<delimiter>')
Example: >> planets2 = dlmread('planets2.txt', ';')
>>load 'filename'
Example: >> load 'planets3.txt'
28
29. >> xlsread: Read files from Excel
Example: >> planets6 = xlsread('planets6.xls')
>> imread: Read graphics file (several formats)
Example: >> planets7 = imread('planets7.jpg');
creates the matrix variable planets7
view with: >> imshow(planets7)
Other special read functions
› aviread [avi audio/visual files]
› textread [read from text file]
› fscanf [read by format, similar to C language
function]
29
30. diary: text file of command window output
>> diary <filename.txt>
….
>> diary off
save: save workspace objects or text to disk
>> save <filename>
Binary file <filename>.mat
>> save <filename>.txt <variable> –ascii -tabs
Text file <filename>.txt
Matrix column elements separated by tabs with -tabs
30
31. Sava data in files:
>> save myfile VAR1 VAR2 …
or
>> save(‘myfile’,’VAR1’,’var2’)
File Formats:
› mat -> Binary MAT-file form
› ascii -> 8-digit ASCII form
› ascii–tabs Delimit array elements with tabs
31
32. Read tables of ASCII data with load
Other functions like textread will read simple
files
Sometimes, you’ve just got to do it yourself
(Complicated files)
To read a file manually, open with fopen
› fid=fopen(‘fname’, ‘rt’);
› fid will be <1 if open fails
› File I/O functions accept fid
› Close the file when you’re done with fclose(fid)
32
33. A=fscanf(fid,cstring,{N})
› like C’s fscanf, cstring is a C format string:
‘%dt%f’--integer (%d),tab(t),double (%f)
lin=fgetl(fid)
› Reads a single line from the file as text (char
array)
› Process lin with str2num, findstr, sscanf
Test for end of file with feof(fid);
33
34. Save matrices using save fname varname
ascii
Doing it yourself:
› fid=fopen(‘fname’,’wt’)
› fprintf(fid,cstring, variables)
› Example:
A=[(1:10)’, sin(2*pi*0.1*(1:10)’)];%[integers,
doubles]
fid=fopen(‘example.txt’,’wt’);
fprintf(fid,’%d %fn’,A’);
fclose(fid);
34
35. Save some images on your desk with
sequential names:
E.g. 1.jpg-2.jpg-3.jpg etc
Im1.tif-Im2.tif-Im3.tif etc
Image1.bmp-Image2.bmp-Image3.bmp etc
Write a program to do the following:
1. Compose the image file path
2. Read the image content
3. Find the image mean value
4. Store the means in a text file ‘MEANS.mat’