+ All Categories
Home > Documents > CSE123 Lecture 6 String Arrays. Character Strings In Matlab, text is referred to as character...

CSE123 Lecture 6 String Arrays. Character Strings In Matlab, text is referred to as character...

Date post: 30-Dec-2015
Category:
Upload: audrey-jenkins
View: 240 times
Download: 2 times
Share this document with a friend
Popular Tags:
23
CSE123 Lecture 6 String Arrays
Transcript

CSE123Lecture 6

String Arrays

Character StringsIn 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>> whosName Size Bytes Classans 1x2 16 double arraytext 1x26 52 char array

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 1284 104 105 115 32 105 115 32 97 32 99 104Columns 13 through 2697 114 97 99 116 101 114 32 115 116 114 105 110 103

ASCII CodesThe 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 1284 104 105 115 32 105 115 32 97 32 99 104Columns 13 through 2697 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 ArraysSince 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 thanone row must have the same numberof columns - just like matrices

>> size(v)ans =3 34

Concatenation of Strings

Because strings are arrays, they may be concatenated (joined) with square brackets.

>> today = ’May’;>> today = [today, ’ 18’]today =May 18

Three blanks??

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.

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 sdistance traveled: 144.6364 ft

String Functionsblanks(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.

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.

CSE123 - Lecture 7CSE123 - Lecture 7

FunctionsFunctions

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)

Functions

>> sqrt(10)

ans = 3.1623

>> SQRT(10)

??? Capitalized internal function SQRT; Caps Lock may be on.

>> sqrt

??? Error using ==> sqrt

Incorrect number of inputs.

>> A=rand(10,10)>> size(A)

ans = 10 10

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 notexist after the function is applied.

d. Output section

Needs to use the OUTPUT variable(s).

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?

areaCircle_Area Area_C Surf_C

Only one: the radius

Only one: the area…

R

A

function OUTPUT=NAME(INPUT)

User defined functions

function A=area(R)

A=pi*R^2;

>> area(1.2)

ans = 4.5239

>> area(1.5)

ans = 7.0686

area.marea.mSaved as

function OUTPUT=NAME(INPUT)

>> area

??? Input argument 'R' is undefined.Error in ==> area at 3

On line 3 ==> A=pi*R^2;

A Rarea

User defined functions

Examples of functions definitions lines:

function TCel=Far2Cel(Tfar)

Convert temperature from Fahrenheit to Celsius. Convert angle from degrees to radians

function Arad=Deg2Rad(Adeg)

Calculate the area and circumference of a rectangle

function [Area,Circ]= RectData(Side1,Side2)

Calculate area and circumference of circle from radius

function [Area,Circ]=Circledata(R)

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 with a meaningful name

•Decide how many inputs:

•Decide how many output:

D2R

1

Arad

Adeg

1

User defined functions

function Arad=d2r(Adeg)

Arad=Adeg*pi/180; d2r.md2r.mSaved as

>> d2r(90)

ans = 1.5708

>> d2r(180)

ans = 3.1416

>> sin( d2r(90) )

ans = 1

>> cos( d2r(180) )

ans = -1

>> disp(Adeg)

??? Undefined function or variable ‘Degree'.

Local variable only exist inside the body of the function

Local variable only exist inside the body of the function

User defined functions

Example 2

Function to calculate the Reynolds number of the flow in a pipe

D)A/M(Re

M: Mass flow rate.A: Cross sectional area of the PipeD: Pipe diameter: Dynamic viscosity of fluid

Define the function with a meaningful name

•Decide how many inputs:

•Decide how many output:

Re1

3

Result

M,D,mu

1

User defined functions

function Result=Re1(M,D,mu)

A=pi*(D/2)^2;

Result=(M/A)*D/mu;

Re1.mRe1.mSaved as

>> Re1(1,2, 9.7720E-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

Local variables only exist inside the body of the function

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.mRe2.mSaved as

>> 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 variablesAll variables inside the body of the function are local variables

User defined functions

function Result=Re3(M,D)

global mu

A=pi*(D/2)^2;

Result=(M/A)*D/mu;

Re3.mRe3.mSaved as

>> global mu

>> mu= 9.7720E-4

>>Re3(1,2)

ans = 651.4734

mu needs to been defined inside and outside as a global variable.

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)]);


Recommended