430 likes | 541 Vues
Computer Programming (ECGD2102 ) Using MATLAB. Lecture (3): MATLAB Environment (Chapter 1). Instructor: Eng. Eman Al.Swaity. Objectives. CHAPTER (1):MATLAB Environment-cont Use strings and perform simple string operations.
E N D
Computer Programming(ECGD2102 ) Using MATLAB Lecture (3): MATLAB Environment (Chapter 1) Instructor: Eng. Eman Al.Swaity
Objectives • CHAPTER (1):MATLAB Environment-cont • Use strings and perform simple string operations. • Perform some basic input/output (I/O) operations using fprintf and input statements. • Creating a script M-file.
1.9 Strings • Strings are matrices with character elements. • String constants are enclosed in single quotes » x='abcd' x = abed
1.9 Strings • How do we create a character string that already contains the single-quote character? As an example, let's specify the string didn't? Two single quotes in a row (' ') give a different result than a double quote (").
1.9 Strings • Escape Characters This table lists the escape character sequences you use to specify nonprinting characters in a format specification. Character Description \b Backspace \f Form feed \n New line \r Carriage return \t Horizontal tab \\ Backslash \ '' or ''(two single quotes)Single quotation mark %% Percent character
1.9 Strings • 1.9.1 String Indexing • The first character of a string has an index of 1. To access any character, we specify the variable name with the index of the character enclosed in parentheses. » a = ‘abed’ a= abed To look at the first character in the string, use index 1. » a(l) ans = a » a(3) ans = e
1.9 Strings • 1.9.2 Concatenating Strings • Strings can be concatenated (that is, linked to make a larger string) by using the following notation: Let's create three strings x1,and x2 » x1='abcd' x1 = abed » x2='efgh' x2 = efgh We will now create a new variable that contains the concatenation of x1 and x2: » x= [x1, x2] x = abedefgh
1.9 Strings • 1.9.2 Concatenating Strings • » mm=['xyzzy',xl,'123',x2] • mm = • xyzzyabed123efgh • » a=[xl(l), x2(1)] • a = • ae • » b=[xl(1:2), x2(1:3)] • b = • abefg
1.9 Strings • 1.9.2 Concatenating Strings
1.9 Strings • 1.9.3 String Functions
1.9 Strings • 1.9.3 String Functions STRREP Replaces characters in a string with different characters. UPPER Converts a string to uppercase. LOWER Converts a string to lowercase. Examples: » a='abedefgh' a = abedefgh » length(a) ans = 8
1.9 Strings • 1.9.3 String Functions num2str converts a number to a string >> msg1 = [’There are ’,num2str(100/2.54),’ inches in a meter’] msg1 = There are 39.3701 inches in a meter For greater control over format of the number-to-string conversion, use The str2num function converts a string representation of a number to its corresponding numeric value. For example, if we add' 123' to '321', we get a strange result: » '123' + '321' ans = 100 100 100
1.9 Strings • 1.9.3 String Functions num2str converts a number to a string >> msg1 = [’There are ’,num2str(100/2.54),’ inches in a meter’] msg1 = There are 39.3701 inches in a meter For greater control over format of the number-to-string conversion, use The str2num function converts a string representation of a number to its corresponding numeric value. For example, if we add' 123' to '321', we get a strange result: » '123' + '321' ans = 100 100 100 This result is actually the sum of the ASCII codes for the two numbers. The first 100 is the ASCII code for 1 plus the ASCII code for 3, …..etc
1.9 Strings • 1.9.3 String Functions The ABS function gets the ASCII codes for a string: » abs('123') ans = 49 50 51 If we want to interpret a string as a number, we use the STR2NUM function to convert the string to a number: » str2num('123') + str2num('321') ans = 444 Function STR2NUM converts the character string '123' to the number 123. » num2str('123') ans = 123
1.9 Strings • 1.9.3 String Functions The char function can be used to combine strings >> both = char(msg1,msg2) both = There are 39.3701 inches in a meter There are 61.02 cubic inches in a liter or to refer to individual characters by their ASCII codes1 >> char(49) ans = 1 >> char([77 65 84 76 65 66]) ans = MATLAB
1.9 Strings • 1.9.3 String Functions Use strcmp to test whether two strings are equal, i.e., if they contain the same sequence of characters. >> msg1 = [’There are ’,num2str(100/2.54),’ inches in a meter’]; >> msg2 =’There are 61.02 cubic inches in a liter’); >> strcmp(msg1,msg2) ans = 0 Compare the first n characters of two strings with strncmp >> strncmp(msg1,msg2,9) ans = 1 The first nine characters of both strings are “There are”, so strncmp(msg1,msg2,9) returns 1, or true.
1.9 Strings • 1.9.3 String Functions Locate occurances of one string in another string with findstr >> msg1 = [’There are ’,num2str(100/2.54),’ inches in a meter’] msg1 = There are 39.3701 inches in a meter >> findstr(’in’,msg1) ans = 19 26 >> msg1(19:20) ans = in
1.9 Strings • 1.9.3 String Functions • The last string function we will look at is STRREP. This function replaces characters in a string with different characters. • » xx='String search and replacement'; • » yy=strrep( xx ,'a', '*') • yy= • String se*rch *nd repl*cement • We can also replace strings of characters with new strings: • » line='supplement replacement excitement retirement'; • » yy=strrep(line, 'ent', '***') • yy = • supplem*** replacem*** excitem*** retirem***
1.10 Input and Output Statements • Every time we make a calculation or assign a variable, MATLAB displays the result automatically. • Everything we have entered has been a one-line calculation. We type in the equation and MATLAB gives us the result. • Most programs, however, ask for input, perform a large number of calculations, and then at the end, display the final results. The intermediate results are not displayed. • This raises the questions: How do we suppress the results of intermediate equations, how does a program request input from the user, and how does a program display results?
1.10 Input and Output Statements 1.10.1 The Semicolon in MATLAB Results of intermediate steps can be suppressed with semicolons. Example: Assign values to x, y, and z, but only display the value of z in the command window: >> x = 5; >> y = sqrt(59); >> z = log(y) + x^0.25 z = 3.5341
1.10 Input and Output Statements 1.10.1 The Semicolon in MATLAB Multiple Statements per Line Use commas or semicolons to enter more than one statement at once. Commas allow multiple statements per line without suppressing output. >> a = 5; b = sin(a), c = cosh(a) b = -0.9589 c = 74.2099
1.10 Input and Output Statements Text Input and Output It is usually desirable to print results to the screen or to a file. On rare occasions it may be helpful to prompt the user for information not already provided by the input parameters to a function. Inputs to functions: • input function can be used • Input parameters to functions are preferred. Text output from functions: • disp function for simple output • fprintf function for formatted output.
1.10 Input and Output Statements 1.10.2 MATLAB Programmed Output • Output to the command window is achieved with either the disp • function or the fprintf function. Output to a file requires the fprintf function. • disp Simple to use. Provides limited control over appearance of output. • fprintf Slightly more complicated than disp. Provides total control over appearance of output.
1.10 Input and Output Statements 1.10.2 MATLAB Programmed Output The fprintf function Syntax: fprintf(outFormat,outVariables) fprintf(fileHandle,outFormat,outVariables) In the first form (no fileHandle) the output is displayed in the command window. In the second form, the output is written to a file referred to by the fileHandle (more on this later). Example: » fprintf('This is a test.\n'); This is a test.
1.10 Input and Output Statements 1.10.2 MATLAB Programmed Output Example:
1.10 Input and Output Statements 1.10.2 MATLAB Programmed Output- Example: » a=3*pi; » b=pi/3; » fprintf('The value of a is %g, the value of b is %g, and that is that.\n', a, b); . The value of a is 9.42478, the value of b is 1.0472, and that is that. Another Example: What is the output?!!
1.10 Input and Output Statements The output is:
1.10 Input and Output Statements we can use a string variable to replace the character string: The two methods produce the same result. The second method can also be used to display the values of variables:
1.10 Input and Output Statements The outFormat string can contain anytext characters. It also must contain a conversion code for each of the outVariables. The following table shows the basic conversion codes.
1.10 Input and Output Statements In addition to specifying the type of conversion (e.g. %d, %f, %e) one can also specify the width and precision of the result of the conversion. Syntax: %wd %w.pf %w.pe where w is the number of characters in the width of the final result, and p is the number of digits to the right of the decimal point to be displayed.
1.10 Input and Output Statements • Conversion specifications begin with the % character and contain these optional and required elements: • Flags (optional) • Width and precision fields (optional) • A subtype specifier (optional) • Conversion character (required) • You specify these elements in the following order: • % - 12.5 e Conversion character • Flag Field width precision
1.10 Input and Output Statements Flags: You can control the alignment of the output using any of these optional flags (- , + ,space , 0) . Field Width and Precision Specifications: You can control the width and precision of the output by including these options in the format string. Conversion Characters: Conversion characters specify the notation of the output.
1.10 Input and Output Statements The disp function Syntax: disp(outMatrix) where outMatrix is either a string matrix or a numeric matrix. Examples: Numeric output Examples: String output
1.10 Input and Output Statements 1.10.3 MATLAB Programmed In put. The input function can be used to prompt the user for numeric or string input. With this function, MATLAB displays the text string and then requests input from you in the form of a number. The value you enter is placed in the variable,
1.10 Input and Output Statements 1.10.3 MATLAB Programmed In put-Examples. Example1 The form of the INPUT function shown previously requires the input of a numerical value. If we type in an invalid response, MATLAB generates an error message and then repeats the message:
1.10 Input and Output Statements Example2
1.10 Input and Output Statements Example3 A second form of the INPUT function allows you to input a character string:
1.13 MATLAB Script Files • A script file is a text file that contains a sequence of MATLAB commands. • Using a script file is equivalent to typing in a series of commands at the MATLAB command prompt, except that you don't need to type the commands each time you wish to use them. • Programs are contained in m-files Plain text files – not binary files produced by word processors File must have “.m” extension • m-file must be in the path
1.13 MATLAB Script Files • Basis for programming • M-files can be: Files that store sequences of commands that can be used over and over User Defined Functions • Go to New to m-file An Editor will open up • Matlab is a scripting language You don’t have to worry about all the standard language overhead!
End of the Lecture Let Learning Continue