代写 matlab Programming MATLAB

Programming MATLAB
Paul Cotofrei
information management institute master of science in finance
2017

Outline
String manipulation

Strings
􏰁 AstringinMATLABconsistsofanynumberofcharactersandis contained in single quotes
􏰁 Stringsarevectorsinwhicheveryelementisasinglecharacter
􏰁 Asubstringisasubsetorpartofastring
􏰁 Charactersincludelettersofthealphabet,digits,punctuation marks, white space, and control characters
􏰁 Control characters are characters that cannot be printed, but accomplish a task (such as a backspace or tab)
􏰁 White space characters include the space, tab, newline, and carriage return
􏰁 Leading blanks are blank spaces at the beginning of a string,
􏰁 Trailing blanks are blank spaces at the end of a string
􏰁 Emptystringisastringwithlength0,e.g.”

Characters and strings
􏰁 Charactersarerepresentedinternallybystandardizednumbers, referred to as ASCII (American Standard Code for Information Interchange) codes
» c = ’A’
c=
A
» x = double(c) x=
65 % ASCII code for ’A’
» char(x) % char() creates a character string
ans =
A
» class(c)
ans =
char

String variables
􏰁 Stringvariablescanbecreatedusing
􏰁 assignment statements
􏰁 input function (with ’s’ as the second argument)
􏰁 Sincestringsarevectorsofcharacters,manybuilt-infunctions and operators work with strings as well as numbers – e.g., length to get the length of a string
􏰁 Youcanalsoindexintoastringvariabletogetindividual characters or to get subsets of strings, or in other words, substrings

Example
» s = ’ABC DEFG’ s=
ABC DEFG
» x = double(s)
x=
65 66 67 32 68 69 70 71 % ASCII codes
» char(x) % convert ASCII codes to characters
ans =
ABC DEFG
» size(s) % s is a row vector of 8 characters
ans =
18 » s(2)
ans = B
» s(3:5) ans =
CD

String concatenation
􏰁 Thereareseveralwaystoconcatenate,orjoin,strings 􏰁 Tohorizontallyconcatenate(createsonelongstring):
􏰁 Using[ ]
» s = [’Albert’, ’Einstein’]
s=
AlbertEinstein
» s = [’Albert’, ’ Einstein’] % leading blank in ’ Einstein’ is preserved s=
Albert Einstein
» s = [’Albert ’, ’Einstein’] % trailing blank in ’Albert ’ is preserved s=
Albert Einstein
» length(s)
ans =
15
􏰁 Using strcat
» s = strcat(’Albert’, ’Einstein’) s=
AlbertEinstein
» s = strcat(’Albert’, ’ Einstein’) s=
AlbertEinstein % leading\trailing blanks are NOT preserved !

Vertical Concatenation
􏰁 Verticallyconcatenatingstringscreatesacolumnvectorofstrings,whichis basically a character matrix (a matrix in which every element is a single character)
􏰁 Using [ ] and separating with semicolons
» s = [’Apple’; ’IBM’; ’Microsoft’];
??? Error using ==> vertcat
CAT arguments dimensions are not consistent.
» s = [’Apple ’; ’IBM ’; ’Microsoft’] % shorter strings must be padded with blank spaces so that all strings are the same length
s=
Apple
IBM
Microsoft
» size(s)
ans =
39
􏰁 Usingchar()orstrvcat()
» s = char(’Apple’, ’IBM’, ’Microsoft’) % no need to pad s=
Apple
IBM
Microsoft
» s = strvcat(’Apple’, ’IBM’, ’Microsoft’) % no need to pad s=
Apple
IBM
Microsoft
» length(s(2, :)) % string ’IBM ’
ans =
9

num2str : Example
􏰁 num2strconvertnumberstoastring
􏰁 Call as num2str(A); num2str(A, precision); num2str(A, format)
» a = [143.87; -0.0000325; -7545]; » s = num2str(a)
s=
143.87
-3.25e-005
-7545
» s = num2str(a, 4) % 4 – max. number of digits s=
143.9
-3.25e-005
-7545
» s = num2str(a, ’%12.6f’) % using format specification s=
143.870000
-0.000032
-7545.000000

String Comparisons
􏰁 Stringsarearraysofcharacters,sotheconditions1==s2requiresboth s1 and s2 to have the same length
» s1 = ’short’; » s2 = ’shore’; » s1==s1
ans =
11111 » s1==s2
ans = 11110
» s1 = ’short’; s2 = ’long’; » s1==s2
??? Error using ==> eq Matrix dimensions must agree.
􏰁 Usestrcmptocomparestringsofunequallength,andgetabinary decision
» s1 = ’short’; » strcmp(s1,s1) ans =
1
» strcmp(s1,s2)
ans = 0
» s1 = ’short’; » strcmp(s1,s2) ans =
s2 = ’shore’;
0
s2 = ’long’;

Some useful string functions
􏰁 Functionsprintf:worksjustlikefprintf,butinsteadofprinting,it
creates a string – so it can be used to customize the format of a string
􏰁 can be used to create customized strings to pass to other functions (e.g. input)
» maxran = randi([1, 50]);
» prompt = sprintf(’Enter an integer from 1 to %d: ’, maxran); » mynum = input(prompt);
Enter an integer from 1 to 46: 33
􏰁 Functionstrtoktakesastringandbreaksitintotwopiecesand returns both strings
􏰁 It looks for a delimiter (by default a blank space) and returns a token which is the beginning of the string up to the delimiter, and also the rest of the string, including the delimiter
» mystring = ’Isle of Skye’;
» [first, rest] = strtok(mystring) % use default delimiter first =
Isle
rest =
of Skye
» [f, r] = strtok(rest, ’y’) % use ’y’ as delimiter f=
of Sk r=
ye

Some useful string functions
􏰁 Theevalfunctionevaluatesastringasafunctioncallora statement
» s = ’sin(pi/2)’;
» eval(s)
ans =
1
» a = 1:4; b = 2;
» s = ’a^b’;
» eval(s)
ans =
1 4 9 16
» x = 1:5;
» fn = input(’Enter a function name: ’, ’s’);
Enter a function name: cos
» eval(strcat(fn, ’(x)’))
ans =
0.5403 -0.4161 -0.9900 -0.6536 0.2837

Other useful string functions
strncmp
Compare first n characters of two strings
strcmpi
Compare two strings ignoring case
strncmpi
Compare first n characters of two strings ignoring case
strfind
Find all occurrences of a substring within the string
strrep
Find and replace substring
strsplit
Split string at delimiter
strtrim
Remove leading and trailing blank space
num2str
Convert numbers to their string representations
str2num
Convert a string representing a numeric value to numeric representation
blanks
Create a string of all blank spaces
deblank
Remove trailing blanks
upper
Convert to upper case
lower
Convert to lower case
isletter
True if the input argument is a letter of the alphabet
isspace
True if the input argument is a white space character
ischar
True if the input argument is a string, or character vector
» doc strfun

Example
􏰁 Thefunctionnamedeptwillreceiveanameanddepartmentas separate strings and will create and return a code consisting of the first two letters of the name and the last two letters of the department. The code should be upper-case letters.
function outcode = namedept(name, department)
name = strtrim(name);
dep = strtrim(department); % remove eventually blank spaces
outcode = upper(strcat(name(1:2), dep(end-1:end)));
end
» namedept(’Peter John’, ’Finance ’)
ans =
PECE

To remember …
􏰁 BewareofCommonPitfalls
􏰁 Trying to use == to compare strings for equality, instead of the strcmp function (and its variations)
􏰁 Confusing sprintf and fprintf. The syntax is the same, but sprintf creates a string whereas fprintf prints
􏰁 Trying to create a column vector of strings with varying lengths (the easiest way is to use char which will pad with extra blanks automatically)
􏰁 Forgetting that when using strtok, the second argument returned (the “rest” of the string) contains the delimiter
􏰁 ProgrammingStyleGuidelines
􏰁 Trim trailing blanks from strings that have been stored in matrices before using
􏰁 Make sure the correct string comparison function is used; for example, strcmpi if ignoring case is desired