4 MATLAB can be used as a scientific calculator,combining several operations in one expression.The computation of the expression is based on well-known mathe matical rules.In particular,some operations are performed before others,based on precedence rules Precedence Operator Parentheses (round brackets) Exponentiation.left to right Multiplication and division.left to right Addition and subtraction.left to right If you want to know the result of the operation (2+[5*3/(7-5)]3)you have to type >(2+(5*3/(7-5)^2)/3) <ENTER> ans、 3.2500 In this example.MATLAB first calculates (7-5)=2.then it squares 22=4.ther it performs the multiplication5*3=15(multiplication left to right).and then divides the result by the previously computed result,i.e.,15/4=3.75.The result in brackets is divided by 3 (3.75/3=1.25)and then added to 2,giving the result.Note that in MATLAB,parentheses are always given by round brackets. MATLAB was developed for scientists,and for this reason you can find built-in operations and functions that are more advanced than the ones we have just looked at.Consider ing MATLAB as a sort of scientific calculator,you can engage the cosine buttor simply by typing: >c03(36) <ENTER> ans -0.1280 Other common functions are reported in the following table.Type the operation after the>>prompt followed by Enter: MATLAB answer Meaning of the operation cos(12) ans=0.8439 Cosine of the element in parentheses 1nt12) n8=-0.5366 Sine of the element in parentheses tan(4) ns=1.1578 Tangent of the element in parentheses exp(3) ans=20.0855 Exponential of the element in parentheses 1og10) n=23026 Natural logarithm of the element in parentheses 1og10(12】 an$=1.0792 Base-10 logarithm of the element in parentheses We will see in the rest of the book the possibility using many other functions Just to introduce some:statistical function functions,fund tions for in ation and last but not least,you own custom-crea ated fur
4 1 Basic Operations MATLAB can be used as a scientifi c calculator, combining several operations in one expression. The computation of the expression is based on well-known mathematical rules. In particular, some operations are performed before others, based on precedence rules, which are given in the following table: Precedence Operator 1 Parentheses (round brackets) 2 Exponentiation, left to right 3 Multiplication and division, left to right 4 Addition and subtraction, left to right If you want to know the result of the operation {2+[5*3/(7−5) 2 ]/3} you have to type: >> (2+(5*3/(7-5)^2)/3) <ENTER> ans = 3.2500 In this example, MATLAB fi rst calculates (7−5) = 2, then it squares 2^2 = 4, then it performs the multiplication 5*3 = 15 (multiplication left to right), and then divides the result by the previously computed result, i.e., 15/4 = 3.75. The result in brackets is divided by 3 (3.75/3 = 1.25) and then added to 2, giving the result. Note that in MATLAB, parentheses are always given by round brackets. MATLAB was developed for scientists, and for this reason you can fi nd built-in operations and functions that are more advanced than the ones we have just looked at. Considering MATLAB as a sort of scientifi c calculator, you can engage the “cosine button” simply by typing: >> cos(36) <ENTER> ans = -0.1280 Other common functions are reported in the following table. Type the operation after the >> prompt followed by Enter: To TYPE after prompt >> followed by Enter MATLAB answer Meaning of the operation cos(12) ans= 0.8439 Cosine of the element in parentheses sin(12) ans= −0.5366 Sine of the element in parentheses tan(4) ans= 1.1578 Tangent of the element in parentheses exp(3) ans= 20.0855 Exponential of the element in parentheses log(10) ans= 2.3026 Natural logarithm of the element in parentheses log10(12) ans= 1.0792 Base-10 logarithm of the element in parentheses We will see in the rest of the book the possibility using many other functions. Just to introduce some: statistical functions, interpolation functions, linear-algebraic functions, functions for images and sound elaboration, and last but not least, your own custom-created functions!
Variables 5 We conclude by giving some hints on creating and editing command lines You can select(and edit)previous commands you have entered using the up- arrow and down-arrow keys.Remember to press Enter to execute the command. MATLAB has a useful editing feature called smart recall.Just type the first few characters of the command you want to recall,e.g.,type the characters 1o and mmand starting with 1o. Variables Thus far,we have seen the use of MATLAB as a scientific calculator.However, MATLAB is much more than a calculator,and the main difference is the possibility to use"variables."In a scientific calculator we can save and recall a single numbe only.In MATLAB.in ast (as in othe r program ming lan ges) es calle obo的ndmeo,b of differen naming it.In such a box you can put the(virtual)item you need,for example a number,an image, and so on. Suppose you want to save a number representing your age.You can create your own variable and store it by simply typing the following command: <ENTER> 22 The symbol age is the variable name(the box name),which contains the numbe 22.Each time you recall(type)such a name,the content of the variable is used;in this simple case,it is displayed.Type again the variable name: >age <ENTER> age= 22 You can define other variables,for example the number of your friends.Just type >Nfriends 132 <ENTER> Nfriends■ 132
Variables 5 We conclude by giving some hints on creating and editing command lines: • You can select (and edit) previous commands you have entered using the uparrow and down-arrow keys. Remember to press Enter to execute the command. • MATLAB has a useful editing feature called smart recall . Just type the fi rst few characters of the command you want to recall, e.g., type the characters lo and press the up-arrow key—this recalls the most recent command starting with lo . The result might be, for example, log(10) or log10(12). Variables Thus far, we have seen the use of MATLAB as a scientifi c calculator. However, MATLAB is much more than a calculator, and the main difference is the possibility to use “variables.” In a scientifi c calculator we can save and recall a single number only. In MATLAB, in contrast (as in other programming languages), we can store and recall virtually an infi nity of different values called variables . A variable is a sort of box, having a certain shape, a certain dimension, with a label naming it. In such a box you can put the (virtual) item you need, for example a number, an image, and so on. Suppose you want to save a number representing your age. You can create your own variable and store it by simply typing the following command: >> age=22 <ENTER> age = 22 The symbol age is the variable name (the box name), which contains the number 22. Each time you recall (type) such a name, the content of the variable is used; in this simple case, it is displayed. Type again the variable name: >> age <ENTER> age= 22 You can defi ne other variables, for example the number of your friends. Just type: >> Nfriends = 132 <ENTER> Nfriends = 132
6 I BasicOperation At this stage,you may wonder about the shape of the box or its volume.The answer is not straightforward.However,by typing the whos command,MATLAB prompts all the variables currently active in the wo orking session >>whos Name cize Bytes Class Attributes age 1×1 8 double Nfriends1×1 8 double and ics.In order to understane the meaning of suck characteristics,consider the analogy between variable and box,as presented in the following table: Variable Box Visual interpretation Name Name of the box Size Number of objects you have put in ase,just one Bytes Total volume of the box.This is the a number you need 8 bytes) Class ct you can put inside it is a number stored with double precision) Attributes Other information Note that the variables list obtained using the command whos can readily be seen in the Workspace Window (see Fig.1.1). One nice thing that MATLAB does when you create a variable is that it automati- cally selects the most suitable type of box for the variable.You need,however.to know a few simple rules about variable names: 1.The variable name mu start with a letter 2.It may consist only of the lettersa.the digits9.and the underscore()You cannot have a name with spaces or others symbols(such as +,^ 3.MATLAB is case-sensitive,which means that it distinguishes between upper and lowercase letters.So age is different from AgE or Age
6 1 Basic Operations At this stage, you may wonder about the shape of the box or its volume. The answer is not straightforward. However, by typing the whos command, MATLAB prompts all the variables currently active in the working session: >> whos <ENTER> Name Size Bytes Class Attributes age 1× 1 8 double Nfriends 1× 1 8 double The whos command gives you a list of all the variables created in the workspace together with their characteristics. In order to understand the meaning of such characteristics, consider the analogy between variable and box, as presented in the following table: Variable Box Visual interpretation Name Name of the box Size Number of objects you have put in (in the previous case, just one object, i.e., 1 × 1). Bytes Total volume of the box. This is the number of objects multiplied by the dimension of each (to store a number you need 8 bytes) Class Type of object you can put inside the box (in the previous case, it is a number stored with double precision ) Attributes Other information Note that the variables list obtained using the command whos can readily be seen in the Workspace Window (see Fig. 1.1 ). One nice thing that MATLAB does when you create a variable is that it automatically selects the most suitable type of box for the variable. You need, however, to know a few simple rules about variable names: 1. The variable name must start with a letter. 2. It may consist only of the letters a–z, the digits 0–9, and the underscore (_). You cannot have a name with spaces or others symbols (such as +, ^, *). 3. MATLAB is case-sensitive, which means that it distinguishes between upperand lowercase letters. So age is different from AgE or Age
Variables 7 Try to create the following variables by typing them after the npt fol. lowed by Enter:N-friends-12,SaDay-60.3rd_classified-11.What hap- pens,and why?MATLAB gives you the following error: ??SaDay=60 Error:The input character is not valid in MATIAB statements or expressions. Obviously.in these examples we didn't follow the aforementioned rules(use of the nd s er MATLAB ha variable names.Some of these are presented in MATLAb answer Value contained in the variable ans=3.1416 ans=2.2204e-016 Floating-point double-precision number =0+1.00001 (-1).used to ans=0+1.0000 ans NaN Not a number Inf ans=inf Infinity You can redefine a variable by simply assigning it a new value: >pi=12 KENTER> pi -12 >pi <ENTER> -12 Once you have insertedanew value.you cannot recall the previous one.Ho weve the predefined variable is restored.To clear variables you use the command clear followed by the variable name (or a list of them).Let's try: >clear pi <ENTER> MATLAB doesn't give you an answer.However,the command has been executed. Type the pi variable again,and MATLAB will return the value of >>pi ans 3.1416
Variables 7 Try to create the following variables by typing them after the >> prompt followed by Enter: N-friends = 12 , $aDay = 60 , 3rd_classified = 11 . What happens, and why? MATLAB gives you the following error: ??? $aDay=60 | Error: The input character is not valid in MATLAB statements or expressions. Obviously, in these examples we didn’t follow the aforementioned rules (use of the character—and $, beginning the name with a number). MATLAB has a few predefi ned variable names. Some of these are presented in the following table: To TYPE after prompt >> followed by Enter MATLAB answer Value contained in the variable Pi ans= 3.1416 p Esp ans= 2.2204e-016 Floating-point relative accuracy, i.e., the distance from 1.0 to the next largest double-precision number j ans= 0+ 1.0000i Imaginary unit, i.e., sqrt(−1), used to enter complex numbers I ans= 0+ 1.0000i Imaginary unit, i.e., sqrt(−1), used to enter complex numbers NaN ans= NaN Not a number Inf ans= inf Infi nity You can redefi ne a variable by simply assigning it a new value: >> pi=12 <ENTER> pi = -12 >> pi <ENTER> pi = -12 Once you have inserted a new value, you cannot recall the previous one. However, in the special case of predefi ned variables, you can clear the redefi ned variable, and the predefi ned variable is restored. To clear variables you use the command clear followed by the variable name (or a list of them). Let’s try: >> clear pi <ENTER> MATLAB doesn’t give you an answer. However, the command has been executed. Type the pi variable again, and MATLAB will return the value of p : >> pi <ENTER> ans = 3.1416
8 I Basic Operations The command clear can be followed by the specification a11,and all the variables stored in the workspace are deleted.To test whether this is indeed the case,type the whos command: >clear all >whos Note that you receive no answer from MATLAB because there is nothing to display. At the same time,you can see that the Workspace Window(Fig.1.1)is empty. With variables you can type complex expressions and store the result.Let's try: >number=13; <ENTER> >a=14; <ENTER> >c=pi+((number+a/2)/10); <ENTER> MATLAB doesn't give an answer because you ended the command with the semicolon which prevents the value of number from being echoed on the screen However,number still has the value 13,as you can see by entering its name without a semicolon (or looking at the Workspace Window): <ENTER> number 3 >>c <ENTER> C= 6.2832 Thinking in a Matrix Way Our first destion abo matrices sWhat is a Matrix?We are not talking ab the fim.the sequels,the muaion that you have ”8am For us,a matrix isn't e to do battl with to save humamy However,you can choose to continue to read the book (in analogy to the blue pill in the film that allows you to lead your normal life)to learn how use MATrix LABoratory to create innovative experiments,thereby changing the world with your discoveries. In MATLAB.a matrix is a rectangular array of numbers.as shown in the follow- ing Fig.1.2. The zontal lines of a matrix are called s,and the vertical lines are called T numbers in the matrix are called en A matrix with m rov is called an mxn matrix.A matrix one of whose dimensions ws andr equals one is often called a vector.An mx I matrix (one column and m rows)is called a column vector,and a Ixn matrix (one row and n columns)is called a row vector
8 1 Basic Operations The command clear can be followed by the specifi cation all , and all the variables stored in the workspace are deleted. To test whether this is indeed the case, type the whos command: >> clear all <ENTER> >> whos <ENTER> >> Note that you receive no answer from MATLAB because there is nothing to display. At the same time, you can see that the Workspace Window (Fig. 1.1 ) is empty. With variables you can type complex expressions and store the result. Let’s try: >> number=13; <ENTER> >> a=14; <ENTER> >> c=pi*((number+a/2)/10); <ENTER> MATLAB doesn’t give an answer because you ended the command with the semicolon (;) which prevents the value of number from being echoed on the screen. However, number still has the value 13, as you can see by entering its name without a semicolon (or looking at the Workspace Window): >> number <ENTER> number = 13 >> c <ENTER> c = 6.2832 Thinking in a Matrix Way Our fi rst question about matrices is, “What is a Matrix?” We are not talking about the fi lm , the sequels, the comic books, or the video games. For us, a matrix isn’t a complex computer simulation that you have to do battle with to save humanity. However, you can choose to continue to read the book (in analogy to the blue pill in the fi lm that allows you to lead your normal life) to learn how use MATrix LABoratory to create innovative experiments, thereby changing the world with your discoveries. In MATLAB, a matrix is a rectangular array of numbers, as shown in the following Fig. 1.2 . The horizontal lines of a matrix are called rows, and the vertical lines are called columns. The numbers in the matrix are called entries. A matrix with m rows and n columns is called an m × n matrix. A matrix one of whose dimensions equals one is often called a vector. An m × 1 matrix (one column and m rows) is called a column vector, and a 1 × n matrix (one row and n columns) is called a row vector