Lab 1: Getting Started With Matlab 1
Lab 1: Getting Started With Matlab 1
1|P a ge
OBJECTIVE: Familiarization with MATLAB: understanding how to perform calculations and usage of branch statements and loops (for/end and while/end) 1.1 BEFORE STARTING CALCULATION how to open MATLAB: On a Unix workstation, MATLAB can be, opened by typing > matlab On a PC, MATLAB can be started by clicking on the start-up menu or a shortcut icon for MATLAB. When MATLAB is started, the window, as illustrated in Figure 1.1, will open. The left side is divided into two sub windows. The right side is the command window, where the most important work for MATLAB is done. Earlier versions did not have such divided subwindows on the left side.
Figure 1.1 MATLAB desktop Once the prompt sign "" appears in the command window, type the commands that are explained throughout this section. On Windows, the initial (default) working directory is C:/MATLAB/bin. If you wish to use a floppy disk as a working directory, type the command to change directory, namely "cd a:", in after the sign, for example cd a: If the working directory is C:/my_directory, type
Numerical Computing
2|P a ge
cd ../.. cd my_directory On Unix, MATLAB can be opened from any directory. To quit MATLAB, type quit help; When the meaning of a command is not clear, type help followed by any command in question. The help command will give you a concise but precise explanation and will be one of the most frequently used commands as you proceed. If you type help date or help format as examples, responses are, respectively, as follows: help DATE Current date as date string. S = DATE returns a string containing the date in dd-mmm-yyyy format. help format FORMAT Set output format. All computations in MATLAB are done in double precision. FORMAT may be used to switch between different output display formats as follows: FORMAT Default. Same as SHORT. FORMAT SHORT Scaled fixed point format with 5 digits. FORMAT LONG Scaled fixed point format with 15 digits. FORMAT SHORT E Floating point format with 5 digits. FORMAT LONG E Floating point format with 15 digits. FORMAT SHORT G Best of fixed or floating point format with 5 digits. FORMAT LONG G Best of fixed or floating point format with 15 digits. FORMAT HEX Hexadecimal format In the online help, keywords are capitalized to make them stand out. Always type commands in lowercase as all command and function names are actually in lowercase. Be aware that the help command is limited to the questions regarding the commands. If you have a question that is more general in nature, click the Help menu on the top menu bar and then click on MATLAB Help. A window as shown in Figure 1.2 will open with the index page already in front. Type the keyword for your question in the small white box under Search index for. The remainder of the process is similar to that of help in MS Windows. 1.2 HOW TO DO CALCULATIONS arithmetic operators: Arithmetic operators +, -, *, and / are, respectively, plus, minus, multiply, and divide, the same as in traditional programming languages. To express power, the operator ^ is used. MATLAB uses one untraditional operator, \, which may be named inverse division. This operator yields the reciprocal of division, that is, a\b equals b/a. For example,
Numerical Computing
3|P a ge
c = 3\1 c= 0.3333
Figure 1.2 calculation with single variables: When a command window is opened, a prompt sign is seen at the upper left corner of the window. Any command can be written after the prompt sign. In the explanation of the commands, however, the prompt sign will be omitted for simplicity. As a simple example, let us evaluate: Volume = (4/3)r3, The commands to type on the screen are: List 1.1a
r = 2; vol = (4/3)*pi*r^3;
with r = 2
where pi = , that is, 3.14159265358979, in MATLAB. Each line is typed after the prompt sign and the return key is hit when finished typing. Notice in the preceding script that each line is a command and completed by a semicolon. The caret symbol ~ after r is the power operator.
Numerical Computing
4|P a ge
When we work in the command window, the computer calculates the answer for each command immediately after the return key is hit. 'Therefore, the value of vol is already in the computer. How can we get the result printed out on the screen? The quickest way of printing out the result is to type vol and hit return. Then the computer prints out vol = 33.510 Another way of printing out the value of vol is to omit the semicolon at the end of the second command List 1.1b
r = 2; vol = (4/3)*pi*r^3
Without a semicolon, the result is printed out immediately after the computation. Because displaying every result is cumbersome, however, we generally place a semicolon after each command. Multiple commands may be written in a single line separated by semicolons. If the results are to be printed out for each command executed, separate commands by commas. The line may be terminated with or without a comma. For example, if you write r = 2, vol = (4/3)*pi*r^3
the values of r and vol are printed out, but if you write r = 2; vol = (4/3)*pi*r^3;
no results are displayed. A long command may be split into multiple lines. In Fortran, it is done by a continuation mark on column 6. In MATLAB, the continuation mark is ... and it is placed at the end of the line to be continued; for example, List 1.2
r = 2; vol = (4/3)*3.14159 ... *r^3;
The prompt sign will not appear in the line following the continuation mark. variables and variable names: Variable names and their types do not have to be declared. This is because variable names in MATLAB make no distinction among integer, real, and complex variables. Any variable can take real, complex, and integer values.
Numerical Computing
5|P a ge
In principle, any name can be used as long as it is compatible in MATLAB. We should, however, be aware of two incompatible situations. The first is that the name is not accepted by MATLAB. The second is that the name is accepted, but it destroys the original meaning of a reserved name. These conflicts can occur with the following types of names: (a) Names for certain values (b) Function (subroutine) names (c) Command names One method to examine compatibility of the variable name is to test it on the command screen. A valid statement such as x=9 is responded to as x= 9 which means that the variable is accepted. If end=4 (a bad example) is attempted, however, it is ignored. An example of the second conflict is as follows: If sin and cos are used (as poor examples of variables) with no relation to the trigonometric functions, for example, sin =3; cos = sin^2; the calculations proceed; however, sin and cos can never be used as trigonometric functions thereafter until variables are cleared by issuing the clear command or MATLAB is shut down. If any error message concerning a conflict appears, the reader should investigate the cause. Traditionally, symbols i, j, k, I, ra, and n have been used as integer variables or indices. At the same time, i and j are used to denote a unit imaginary value, or . In MATLAB, i and j are reserved as unit imaginary value. Therefore, if the computation involves complex variables, it is advisable to avoid i and j as user-defined variables. Table 1.1 lists samples of reserved variable names that have special meanings. Whether a variable or filename exists may also be checked by using the exist command. For more details, type help exist. format: Numbers displayed are five-digit numbers by default: pi ans = 3.1416 The same numbers, however, may be displayed with 16 digits after the command format long; for example, format long pi ans = 3.141592653589793
Numerical Computing
6|P a ge
In order to return to the short format, use format short. Also, with format short e and format long e, respectively, short and long numbers are printed in floating-point format. clear: As you execute commands, MATLAB memorizes the variables used. Their values stay in memory until you quit MATLAB or clear the variables. To clear all the variables, use the clear command. If only certain variables are to be cleared, name the variables after clear; for example, clear x y z clc: If you wish to clear a window, use the command clc.
Variable name eps Pi i and j inf NaN date flops nargin nargout
Meaning Machine epsilon Unit imaginary Infinity Not a number Date Floating point operation count Number of function input arguments Same for output
Table 1.1 Special Numbers and Variable Names 1.3 BRANCH STATEMENTS if, else, elsif, end: An if statement is always closed with an end statement; for example, List 1.3
n = 2; %(Assume n is a user input so it may be changed) if n<=5, price=15; elseif n>5, price=12; end
Here the line starting elseif can be eliminated if not needed. Do not separate elseif into two words. Of course, elseif can be repeated when necessary. Notice also in writing the foregoing
Numerical Computing
7|P a ge
script that the prompt sign does not appear after if until end is typed. The foregoing script may be equivalently written as n = 2; % (Assume n is a user input so it may be changed) if n<=5, price=15; else price=12; end When the if statement needs to examine the equality of two terms, use "=="as in the C language; for example, List 1.4
n = 2; if n==2, end
price=17;
vol =
(4/3)*pi*r^3;
The greater than, less than, equal or greater than, and equal or less than operators are, respectively, > < >= <= The logical statements and and or are denoted by & and |, respectively. For example, the conditional equation, if g > 3 or g < 0, then a = 6 is written as if g>3 | g<0, a = 6; end Also, the conditional equation if a > 3 and c < 0, b = 19 is stated as if a>3 & c<0, b=19; end
Numerical Computing
8|P a ge
The & and I operators can be used in a clustered form, for example, if ((a==2 | b==3) & c<5) g=l; end ______________________________________________________________________________ Example 1.1 Assuming two arbitrary integers, R and D, are given in the beginning of the script, write a script that prints out only if R is divisible by D = 3. Solution Two equivalent ways to examine if R is divisible by another number are: (1) fix(R/D)=R/D , and (2) mod(R,D)=0. Here, fix(x) returns the integer part of the number x, while mod(x,y) returns the remainder on division of x by y. Therefore, a script based on (1) is: List 1.6a
R=45; D=3; if fix(R/D) == R/D,
R,
end
== 0,
R,
end
______________________________________________________________________________ 1.4 LOOPS WITH for/end OR while/end loops: MATLAB has for/end and while/end loops. To illustrate a for/end loop, let us look at the following script that calculates y = x2 5x 3 for each of x = 1,2..9 in increasing order. List 1.7a
for z=l:9 y=x^2 - 5*x - 3 end
Notice that for is terminated by end. In the first cycle, x is set to 1, and y is calculated. In the second cycle, x is set to 2 (with an increment of 1), and y is calculated. The same is repeated until the calculation of y is completed for the last value of x. If x is to be changed with a different increment, the increment can be specified between the initial and last number as follows: List 1.7a
for x=l:0.5:9 y=x^2 - 5*x - 3
Numerical Computing
9|P a ge
where the increment is now 0.5. The order of calculation in the loop can be reversed as follows: List 1.7b
for x=9:-l:l y = x^2 - 5*x - 3 end
Here, the middle number -1 in 9:-l:l is the increment in changing x. It is also possible to compute for any sequence of specified values of x, for example: List 1.7c
for x=[-2 0 15 6] y = x^2 - 5*x - 3 end
Here, y is computed for x =-2 first, which is followed by x =0, 15, and 6. The if/end statement can be inserted in the loop. In the following example, y = sin(x) if sin (x) > 0 but y = 0 if sin(x) < 0. List 1.7d
for x=0:0.1:10 y=sin(x); if y<0, y=0;end y end
In the following script, c=0 initializes the counter c to zero, x= [-8, . . ] defines an array of the numbers, and length (x) is the length of the array x. In the for/end loop the counter c is incremented by one if x(i) is negative. Finally, c prints out the count of the negative elements. List 1.7e
c=0; x=[-8, 0, 2, for i=1: length (x) if x(i)<0, c=c+1; end end c 5, 7, 2, 0, 0, 4, 6, 6, 9];
In this example, -1 between two colon operators is the decrement of the parameter i after each cycle of the loop operation.
Numerical Computing
10 | P a g e
An alternative way of writing a loop is to use the while/end; for example, List 1.9
i = 0;c=0; x=[-8, 0, 2, while i<length(x)+l if x(i)<0, c=c+l; end end c 5, 7, 2, 0, 0, 4, 6, 6, 9] ;
Example 1.2 Write a script that removes the numbers divisible by 4 from an array x. Assume the array x is given by x=[-8, 0, 2, 5, 7, 2, 0, 0, 4, 6, 6, 9] Solution The script to the answer is List 1.9
x=[-8, y=[]; for n=1: length (x) if x(n)/4 - fix(x(n)/4)~=0 end y y=[y,x(n)]; end 0, 2, 5, 7, 2, 0, 0, 4, 6, 6, 9] ;
In the foregoing script, fix(x(n)/4) equals the integer part of x(n)/4, so fix(x(n)/4)-x(n)/4=0 is satisfied if x(n) is divisible by 4. Equivalently, mod(a,b) may be used that equals zero if a is divisible by b. The following script shows alternative programming to achieve the same end:
List 1.9
x=[-8, 0, 2, 5, for n=l:length(x) if mod(x(n),4)=0 x(n) = []; end end x 7, 2, 0, 0, 4, 6, 6, 9];
The result is
Numerical Computing
11 | P a g e
y= 2 5 7 2 6 6 9
break: The break terminates the execution of a for or while loop. When used in nested loops, only the immediate loop where break is located is terminated. In the next example, break terminates the inner loop as soon as j>2*i is satisfied once, but the loop for i is continued until i=6: List 1.10
for i=l:6 for j=l:20 if j>2*i, break, end end end
. In the foregoing loop, the radius r is typed through the keyboard. The fprintf statement is to print out vol with a format, %7.3f, which is equivalent to F7.3 in Fortran. If 0 < r < 10, vol is computed and printed out, but if r < 0 the loop is terminated. Also, if r < 10 is dissatisfied once, the while loop is terminated. More explanations for input and fprintf are given in next practical. In a programming language that has no break command, goto would be used to break a loop. MATLAB, on the other hand, has no goto statement. infinite loop: Sometimes a loop that can continue infinitely is used, which may be terminated when a certain condition is met. The following example shows an infinite loop that is broken only if the condition x > xlimit is met: while 1 . . if x > xlimit, break; end . . end
______________________________________________________________________________
Numerical Computing
12 | P a g e
TASKS: (1.1) Eliminate the for/end loop in the following script by using the array arithmetic operators:
x=11:15 for k=l: length (x) z(k)=x(k)^2 + 2.3*x(k)^0.5; end z
(1.2) A vector is given by a = [4 -1 2 -8 4 5 -3 -1 6 -7] Write a script that doubles the negative numbers in a. Run the script and show your output. (1.3) Write a script that removes positive numbers from a given in Problem (1.2). Run the script and show your printout of the answer. (1.4) A company selling printer cartridges has the following price policy. The first cartridge is $50, the second is $35, but the third one is free. This pricing pattern repeats as the number of cartridges sold increases, namely, the fourth is $50, the fifth is $35 and the sixth is free, and so on. Most customers buy multiples of three to take advantage of every third. However, large organizations like universities and government agencies buy the exact number of cartridges they need regardless of the advantage of the free purchase. Thus, the company must prepare a price chart for any number of cartridges sold. Write a script to prepare a price chart for up to 20 cartridges. Make sure the output of your chart is correct by hand calculations.
Numerical Computing