CSE 123 Lecture 6 String Arrays Character Strings

  • Slides: 23
Download presentation
CSE 123 Lecture 6 String Arrays

CSE 123 Lecture 6 String Arrays

Character Strings In Matlab, text is referred to as character strings. String Construction Character

Character Strings In Matlab, text is referred to as character strings. String Construction Character strings in Matlab are special numerical arrays of ASCII values that are displayed as their character string representation. For example: >> text = ’This is a character string’ text = This is a character string >> size(text) ans = 1 26 >> whos Name Size Bytes Class ans 1 x 2 16 double array text 1 x 26 52 char array

ASCII Codes • Each character in a string is stored in two bytes per

ASCII Codes • Each character in a string is stored in two bytes per character for storage, using the ASCII code. • Numerical or double arrays is stored in eight bytes per element required for numerical or double arrays. • The ASCII codes for the letters ‘A’ to ‘Z’ are the consecutive integers from 65 to 90, while the codes for ‘a’ to ‘z’ are 97 to 122. • The function abs returns the ASCII codes for a string. text = ’This is a character string’ text = This is a character string >> d = abs(text) d = Columns 1 through 12 84 105 115 32 97 32 99 104 Columns 13 through 26 97 114 97 99 116 101 114 32 115 116 114 105 110 103

ASCII Codes The function abs returns the ASCII codes for a string. text =

ASCII Codes The function abs returns the ASCII codes for a string. text = ’This is a character string’ text = This is a character string >> d = abs(text) d = Columns 1 through 12 84 105 115 32 97 32 99 104 Columns 13 through 26 97 114 97 99 116 101 114 32 115 116 114 105 110 103 The function char performs the inverse transformation, from ASCII codes to a string: >> char(d) ans = This is a character string

Strings are Arrays Since strings are arrays, they can be manipulated with array manipulation

Strings are Arrays Since strings are arrays, they can be manipulated with array manipulation tools: >> text = ’This is a character string’; >> u = text(11: 19) u = character As with matrices, character strings can have multiple rows, but each row must have an equal number of columns. Therefore, blanks are explicitly required to make all rows the same length. >> v = [’Character strings having more than’ ’one row must have the same number ’ ’of columns - just like matrices ’] v = Character strings having more than one row must have the same number of columns - just like matrices >> size(v) ans = 3 34

Concatenation of Strings Because strings are arrays, they may be concatenated (joined) with square

Concatenation of Strings Because strings are arrays, they may be concatenated (joined) with square brackets. Three blanks? ? >> today = ’May’; >> today = [today, ’ 18’] today = May 18

String Conversions char(x) Converts : that contains array the x positive integers representing character

String Conversions char(x) Converts : that contains array the x positive integers representing character codes into a character array (the first 127 codes are ASCII). int 2 str(x): Rounds the elements of the matrix x to integers and converts the result into a string matrix. num 2 str(x): Converts the matrix x into a string representation with about 4 digits and an exponent if required. str 2 num(s): Converts the string s to numeric representation. The string may contain digits, a decimal point, a leading + or - sign, or ’e’ power of 10 scale factor.

String Conversions • The num 2 str function can be used to convert numerical

String Conversions • The num 2 str function can be used to convert numerical results into strings for use in formating displayed results with disp. tg = 2. 2774; xg = 144. 6364; disp([’time of flight: ’ num 2 str(tg) ’ s’]) disp([’distance traveled : ’ num 2 str(xg) ’ ft’]) time of flight: 2. 2774 s distance traveled: 144. 6364 ft

String Functions : Returns a string of n blanks. Used with disp, eg. Disp

String Functions : Returns a string of n blanks. Used with disp, eg. Disp ([’xxx’blanks(20) ’yyy’]). disp(blanks(n)’) moves the cursor down n lines. deblank(s) : Removes trailing blanks from string s. eval(s) : Execute the string s as a Matlab expression or statement. eval(s 1, s 2) : Provides the ability to catch errors. Executes string s 1 and returns if the operation was successful. If the operation generates an error, string s 2 is evaluated before returning. This can be thought of as eval(’try’, ’catch’). findstr(s 1, s 2) : Find one string within another. Returns the starting indices of any occurrences of the shorter of the two strings in the longer. ischar(s) : Returns 1 if s is a character array and 0 otherwise. isletter(s) : Returns 1 for each element of character array s containing letters of the alphabet and 0 otherwise. isspace(s) : Returns 1 for each element of character s containing white space characters and 0 otherwise. White space characters are spaces, newlines, carriage returns, tabs, vertical tabs, and formfeeds. lasterr : Returns a string containing the last error message issued. lasterr isusually used in conjunction with the two argument form of eval: eval(’try’, ’catch’). The ’catch’ action can examine the lasterr string to determine the cause of the error and take appropriate action. blanks(n)

String Functions : Converts any uppercase characters in string s to the corresponding lowercase

String Functions : Converts any uppercase characters in string s to the corresponding lowercase character and leaves all other characters unchanged. strcat(s 1, s 2, . . ) : Horizontally concatenates corresponding rows of the character arrays s 1, s 2, s 3 etc. The trailing padding is ignored. All the inputs must have the same number of rows (or any can be a single string). When the inputs are all character arrays, the output is also a character array. strcmp(s 1, s 2) : Returns 1 if strings s 1 and s 2 are identical and 0 otherwise. strjust(s) : Returns a right justified version of the character array s. strmatch(str, strs) : Searches through the rows of the character array of strings strs to find strings that begin with string str, returning the matching row indices. strncmp(s 1, s 2, n) : Returns 1 if the first n characters of the strings s 1 and s 2 are identical and 0 otherwise. strrep(s 1, s 2, s 3) : Replaces all occurrences of the string s 2 in string s 1 with the string s 3. The new string is returned. upper(s) : Converts any lower case characters in s to the corresponding upper case character and leaves all other characters unchanged. lower(s)

CSE 123 - Lecture 7 Functions

CSE 123 - Lecture 7 Functions

Functions >> SQRT(10) Functions Ex: Already defined functions: sin, cos, tan, sqrt… ? ?

Functions >> SQRT(10) Functions Ex: Already defined functions: sin, cos, tan, sqrt… ? ? ? Capitalized internal function SQRT; Caps Lock may be on. Specifications >> sqrt ? ? ? Error using ==> sqrt • Usually have a meaningful name (case sensitive) function sqrt is not the same as SQRT • Need an argument, or parameter to work. sqrt(10) Incorrect number of inputs. >> sqrt(10) ans = 3. 1623 sin(2*pi/180) • Can give multiple answers or results, usually as a vector (or matrix) >> A=rand(10, 10) >> size(A) ans = 10 10

User defined functions How to create a user-defined function • Exactly like script (.

User defined functions How to create a user-defined function • Exactly like script (. m file) • Start with a function definition line Typical structure of a user-defined function a. Function definition line (required): function OUTPUT=NAME(INPUT) b. Comment Section (information on the program) c. Calculation section Unless specified, every variable is local and therefore will not exist after the function is applied. d. Output section Needs to use the OUTPUT variable(s).

User defined functions Same specifications • Define the function with a meaningful name •

User defined functions Same specifications • Define the function with a meaningful name • Decide how many arguments (or input) • Decide how many results (or output) Ex: Define a function that calculates the area of the circle based on its radius. • Name? Circle_Area_C Surf_C area • How many input? Only one: the radius R • How many output? Only one: the area… A function OUTPUT=NAME(INPUT)

User defined functions function OUTPUT=NAME(INPUT) A area R function A=area(R) Saved as area. m

User defined functions function OUTPUT=NAME(INPUT) A area R function A=area(R) Saved as area. m A=pi*R^2; >> area(1. 2) >> area ans = ? ? ? Input argument 'R' is undefined. Error in ==> area at 3 4. 5239 On line 3 ==> A=pi*R^2; >> area(1. 5) ans = 7. 0686

User defined functions Examples of functions definitions lines: Convert temperature from Fahrenheit to Celsius.

User defined functions Examples of functions definitions lines: Convert temperature from Fahrenheit to Celsius. function TCel=Far 2 Cel(Tfar) Convert angle from degrees to radians function Arad=Deg 2 Rad(Adeg) Calculate area and circumference of circle from radius function [Area, Circ]=Circledata(R) Calculate the area and circumference of a rectangle function [Area, Circ]= Rect. Data(Side 1, Side 2) Calculate the arithmetic and the geometric mean of a series of number function [Amean, Gmean]=Means(A)

User defined functions Example 1 Convert angle from degrees to radians Define the function

User defined functions Example 1 Convert angle from degrees to radians Define the function with a meaningful name D 2 R • Decide how many inputs: 1 Adeg • Decide how many output: 1 Arad

User defined functions function Arad=d 2 r(Adeg) Arad=Adeg*pi/180; Saved as d 2 r. m

User defined functions function Arad=d 2 r(Adeg) Arad=Adeg*pi/180; Saved as d 2 r. m >> d 2 r(90) >> disp(Adeg) ans = ? ? ? Undefined function or variable ‘Degree'. 1. 5708 >> d 2 r(180) ans = 3. 1416 >> sin( d 2 r(90) ) ans = 1 >> cos( d 2 r(180) ) ans = -1 Local variable only exist inside the body of the function

User defined functions Example 2 Function to calculate the Reynolds number of the flow

User defined functions Example 2 Function to calculate the Reynolds number of the flow in a pipe M: Mass flow rate. A: Cross sectional area of the Pipe D: Pipe diameter : Dynamic viscosity of fluid Define the function with a meaningful name Re 1 • Decide how many inputs: 3 M, D, mu • Decide how many output: 1 Result

User defined functions function Result=Re 1(M, D, mu) A=pi*(D/2)^2; Saved as Re 1. m

User defined functions function Result=Re 1(M, D, mu) A=pi*(D/2)^2; Saved as Re 1. m Result=(M/A)*D/mu; >> Re 1(1, 2, 9. 7720 E-4 ) ans =651. 4734 >> disp(A) ? ? ? Undefined function or variable 'A'. >> disp(Result) ? ? ? Undefined function or variable ‘Result'. Local variables only exist inside the body of the function

User defined functions function Result=Re 2(M, D, q) % q values: (1) for water

User defined functions function Result=Re 2(M, D, q) % q values: (1) for water and (2) for air Saved as Re 2. m A=pi*(D/2)^2; if q==1 mu= 9. 7720 E-4 ; else mu= 1. 8205 E-5; end Result=(M/A)*D/mu; >> Re 2(1, 2, 1) ans = 651. 4734 >> Re 2(1, 2, 2) ans = 3. 4970 e+004 All variables inside the body of the function are local variables

User defined functions function Result=Re 3(M, D) global mu Saved as Re 3. m

User defined functions function Result=Re 3(M, D) global mu Saved as Re 3. m A=pi*(D/2)^2; Result=(M/A)*D/mu; >> global mu >> mu= 9. 7720 E-4 mu needs to been defined inside and outside as a global variable. >>Re 3(1, 2) ans = 651. 4734

Example for Functions Distance between two points function distance=dist 2(x 1, y 1, x

Example for Functions Distance between two points function distance=dist 2(x 1, y 1, x 2, y 2) %DIST 2 calculate the distance between two points distance= sqrt((x 2 -x 1). ^2+(y 2 -y 1). ^2); A simple script calling this function test_dist 2. m disp('calculate the distance between two points') ax=input('enter x value of first point'); ay=input('enter y value of second point'); bx=input('enter x value of first point'); by=input('enter y value of second point'); result=dist 2(ax, ay, bx, by); disp(['the distance between two points is : ', num 2 str(result)]);