1 / 23

CSE123 Lecture 6

CSE123 Lecture 6. String Arrays. 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:.

adair
Download Presentation

CSE123 Lecture 6

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CSE123Lecture 6 String Arrays

  2. 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 1x2 16 double array text 1x26 52 char array

  3. 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 104 105 115 32 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

  4. 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 104 105 115 32 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

  5. 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

  6. 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

  7. String Conversions char(x) : Converts the array x that contains positive integers representing character codes into a character array (the first 127 codes are ASCII). int2str(x): Rounds the elements of the matrix x to integers and converts the result into a string matrix. num2str(x): Converts the matrix x into a string representation with about 4 digits and an exponent if required. str2num(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.

  8. String Conversions • The num2str 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: ’ num2str(tg) ’ s’]) disp([’distance traveled : ’ num2str(xg) ’ ft’]) time of flight: 2.2774 s distance traveled: 144.6364 ft

  9. String Functions blanks(n) :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(s1,s2) :Provides the ability to catch errors. Executes string s1 and returns if the operation was successful. If the operation generates an error, string s2 is evaluated before returning. This can be thought of as eval(’try’,’catch’). findstr(s1,s2) :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.

  10. String Functions lower(s) :Converts any uppercase characters in string s to the corresponding lowercase character and leaves all other characters unchanged. strcat(s1,s2,..) :Horizontally concatenates corresponding rows of the character arrays s1, s2, s3 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(s1,s2) :Returns 1 if strings s1 and s2 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(s1,s2,n) :Returns 1 if the first n characters of the strings s1 and s2 are identical and 0 otherwise. strrep(s1,s2,s3) :Replaces all occurrences of the string s2 in string s1 with the string s3. 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.

  11. CSE123 - Lecture 7 Functions

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

  13. 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) • Comment Section (information on the program) • Calculation section Unless specified, every variable is local and therefore will not exist after the function is applied. • Output section • Needs to use the OUTPUT variable(s).

  14. User defined functions • 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? • How many input? • How many output? Circle_Area Area_C Surf_C area Only one: the radius R Only one: the area… A function OUTPUT=NAME(INPUT)

  15. Saved as User defined functions function OUTPUT=NAME(INPUT) A area R function A=area(R) A=pi*R^2; area.m >> area(1.2) ans = 4.5239 >> area(1.5) ans = 7.0686 >> area ??? Input argument 'R' is undefined. Error in ==> area at 3 On line 3 ==> A=pi*R^2;

  16. User defined functions Examples of functions definitions lines: Convert temperature from Fahrenheit to Celsius. Convert angle from degrees to radians function TCel=Far2Cel(Tfar) function Arad=Deg2Rad(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]= RectData(Side1,Side2) Calculate the arithmetic and the geometric mean of a series of number function [Amean,Gmean]=Means(A)

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

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

  19. 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 • Decide how many inputs: • Decide how many output: Re1 3 M,D,mu 1 Result

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

  21. Saved as User defined functions function Result=Re2(M,D,q)% q values: (1) for water and (2) for air A=pi*(D/2)^2; if q==1 mu= 9.7720E-4 ; else mu= 1.8205E-5; end Result=(M/A)*D/mu; Re2.m >> Re2(1,2,1) ans = 651.4734 >> Re2(1,2,2) ans = 3.4970e+004 All variables inside the body of the function are local variables

  22. Saved as User defined functions function Result=Re3(M,D) global mu A=pi*(D/2)^2; Result=(M/A)*D/mu; Re3.m >> global mu >> mu= 9.7720E-4 >>Re3(1,2) ans = 651.4734 mu needs to been defined inside and outside as a global variable.

  23. Example for Functions Distance between two points function distance=dist2(x1,y1,x2,y2) %DIST2 calculate the distance between two points distance= sqrt((x2-x1).^2+(y2-y1).^2); A simple script calling this function test_dist2.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=dist2(ax,ay,bx,by); disp(['the distance between two points is :', num2str(result)]);

More Related