MATLAB® Basics

MATLAB® Basics

CHAPTER MATLAB® Basics 1 CHAPTER OUTLINE 1.1 Getting Started with the MATLAB® Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.2...

3MB Sizes 5 Downloads 210 Views

CHAPTER

MATLAB® Basics

1

CHAPTER OUTLINE 1.1 Getting Started with the MATLAB® Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.2 MATLAB® as a Calculator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.3 Logical Expressions and Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

3 4 9

Motivation This chapter gets you started with MATLAB, using it as a calculator. As you will see, MATLAB has a large library of built-in mathematical functions that you can use to perform any operation available on a scientific or graphing calculator. At the end of this chapter, you should be familiar with the MATLAB environment, how to execute commands to MATLAB, and MATLAB’s basic mathematical functionalities.

1.1 Getting Started with the MATLAB® Environment Once MATLAB is installed on your computer, you should see a shortcut on the desktop that looks like . Double-clicking the shortcut icon will open the MATLAB environment shown in Figure 1.1. The MATLAB environment is a text-based visualization tool that allows you to interact with MATLAB. The MATLAB environment consists of the current directory as well as four windows: the command window, the current directory window, the workspace window, and the command history window. They are shown in Figure 1.1. The current directory is the folder in your computer where files will be saved and where the files you will have direct access to are stored. You can change the current directory by clicking the down arrow or the button with an ellipsis symbol (…). The current directory will be explained in greater detail in Chapter 3 on Functions. The command window is the window in the MATLAB environment where commands are executed and MATLAB’s responses are displayed. The command prompt is where you can type your commands in the command window and is denoted by the symbol ». When you see this symbol in the text or in examples, it means that the action is taking place at the command window. The current directory window is the window in the MATLAB environment that lists all the files currently An Introduction to MATLAB® Programming and Numerical Methods. http://dx.doi.org/10.1016/B978-0-12-420228-3.00001-4 © 2015 Elsevier Inc. All rights reserved.

3

4

CHAPTER 1 MATLAB® Basics

FIGURE 1.1 The MATLAB environment.

stored in the current directory. The workspace window is the window in the MATLAB environment that lists all the variables currently being used in the workspace. The details of the workspace will also be explained in Chapter 3 on Functions. The command history window is the window in the MATLAB environment that lists all the previous commands entered at the command prompt, which is helpful for recalling work that was done in a previous session. You can rearrange the size and shape of the windows by clicking and holding the mouse cursor on the borders of the windows, and then dragging them to a location that suits you better. You can also change the location of the windows by clicking and holding the mouse cursor on the window title bar, and dragging it to a different location. If you wish to remove a window, click the X in the upper right corner of the window. To put it back, click Desktop in the menu bar and then click the window you want. TIP! You can change the background color as well as the font color and style to suit your personal preference. The options can be changed in the File → Preferences menu in the upper left hand corner of the MATLAB environment.

1.2 MATLAB® as a Calculator We will introduce you to MATLAB by demonstrating features found in any standard graphing calculator. An arithmetic operation is either addition, subtraction, multiplication, division, or powers between

1.2 MATLAB® as a Calculator

5

two numbers. An arithmetic operator is a symbol that MATLAB has reserved to mean one of the aforementioned operations. These symbols are + for addition, − for subtraction, ∗ for multiplication, / for division, and ˆ for exponentiation. We say an instruction or operation is executed when it is resolved by the computer. An instruction is executed at the command prompt by typing it where you see the » symbol and then pressing Enter. TRY IT! Compute the sum of 1 and 2.

An order of operations is a standard order of precedence that different operations have in relationship to one another. MATLAB utilizes the same order of operations that you learned in grade school. Powers are executed before multiplication and division, which are executed before addition and subtraction. Parentheses, (), can also be used in MATLAB to supercede the standard order of operations. TRY IT! Compute

3∗4 . 22 +4/2

TIP! You may have noticed ans is the resulting value of the last operation executed. You can use ans to break up complicated expressions into simpler commands.

TRY IT! Compute 3 divided by 4, then multiply the result by 2, and then raise the result to the 3rd power.

MATLAB has many basic arithmetic functions like sin, cos, tan, asin, acos, atan, exp, log, log10, and sqrt. The inputs to these mathematical functions are always placed inside of parentheses that are connected to the function name. For trigonometric functions, it is useful to have the value of π easily available. You can call this value at any time by typing » pi in the command prompt. Note that the value of π is stored in MATLAB to 16 digits.

6

CHAPTER 1 MATLAB® Basics

TRY IT! Find the square root of 4.

TRY IT! Compute the sin

π  2 .

TIP! Sometimes you may wish to view more or less digits than MATLAB’s default setting of four decimal places. There are many different number viewing options in MATLAB but for the purposes of this text, we will restrict these options to “short,” “long,” and “bank” unless you are specifically told otherwise. The short format is MATLAB’s default setting. It displays all numbers to four significant figures. The long format displays the maximum number of digits that MATLAB can store, which is 16. The bank format displays exactly two. You can change the formatting by typing of the following commands:

Note that this changes only how the numbers are displayed; it does not alter the actual value being used.

TRY IT! Call MATLAB’s stored value for π using format long, format bank, and format short.

MATLAB will compose functions as you would expect, with the innermost function being executed first. The same holds true for function calls that are composed with arithmetic operations.

1.2 MATLAB® as a Calculator

7

TRY IT! Compute elog 10 .

3

TRY IT! Compute e 4 .

Note that the log function in MATLAB is loge , or the natural logarithm. It is not log10 . If you want to use log10 , you need to use log10.

TIP! Using the UP ARROW in the command prompt recalls previous commands that were executed. If you accidentally type a command incorrectly, you can use the UP ARROW to recall it, and then edit it instead of retyping the entire line.

The help function is a command that can be used to view the description of any function in MATLAB. You can call the help function by typing » help at the command prompt and then the name of the function. If you see a function you are unfamiliar with, it is good practice to use the help function before asking your instructors what a specific function does. At the end of every chapter in this book is a section called “Functions and Operators,” which lists the new functions and operations presented in the chapter. If you are uncertain what these functions do, use the help function to learn about them.

WARNING! For some functions, the help file can be extremely complicated and wordy, even for simple functions. In these cases, do not be afraid to ask your instructor for help.

TRY IT! Use the help function to find the definition of the factorial function.

8

CHAPTER 1 MATLAB® Basics

TIP! Use the format compact command to reformat text so that you have only a single space between commands instead of the default setting of double space. You can change the spacing format using the command » format compact; to change it back, use » format loose.

MATLAB can handle the expression 1/0, which is infinity. Note that MATLAB will return 0/0 as “not a number” or NaN. You can type Inf at the command prompt to denote infinity or NaN to denote something that is not a number that you wish to be handled as a number. If this is confusing, this distinction can be skipped for now; it will be explained more clearly √ when it becomes important. Finally, MATLAB can also handle the imaginary number, i, which is −1. You can type » i to recall the stored value of i just like π . TRY IT! Compute 1/0, 1/∞, and ∞ · 2 to verify that MATLAB handles infinity as you would expect.

TRY IT! Compute ∞/∞.

TRY IT! Verify that MATLAB’s stored value for i squares to −1.

1.3 Logical Expressions and Operators

9

TRY IT! Compute the imaginary sum 2 + 5i.

MATLAB can also handle scientific notation using the letter e between two numbers. For example, » 1e6 is 1 × 106 = 1000000 and » 1e-3 is 1 × 10−3 = 0.001.

TRY IT! Compute the number of seconds in 3 years using scientific notation.

1.3 Logical Expressions and Operators A logical expression is a statement that can either be true or false. For example, a < b is a logical expression. It can be true or false depending on what values of a and b are given. Note that this differs from a mathematical expression which denotes a truth statement. In the previous example, the mathematical expression a < b means that a is less than b, and values of a and b where a ≥ b are not permitted. Logical expressions form the basis of computing, so for the purposes of this book, all statements are assumed to be logical rather than mathematical unless otherwise indicated. In MATLAB, a logical expression that is true will compute to the value “TRUE.” A false expression will compute to the value “FALSE.” For the purpose of this book, “TRUE” is equivalent to 1, and “FALSE” is equivalent to 0. Distinguishing between the numbers 1 and 0 and the logical values “TRUE” and “FALSE” is beyond the scope of this book, but it is covered in more advanced books on computing. Logical expressions are used to pose questions to MATLAB. For example, “3 < 4” is equivalent to, “Is 3 less than 4?” Since this statement is true, MATLAB will compute it as 1. However, 3 > 4 is false, therefore MATLAB will compute it as 0. Comparison operators compare the value of two numbers, and they are used to build logical expressions. MATLAB reserves the symbols >, >=, <, <=, ∼=, ==, to denote “greater than,” “greater than or equal,” “less than,” “less than or equal,” “not equal,” and “equal,” respectively.

10

CHAPTER 1 MATLAB® Basics

(a)

1

1

0

Q

Q

0

(b)

1

1

0

1

1

1

0

0

0

1

0

P

0

P

AND

OR

FIGURE 1.2 Truth tables for the logical AND and OR.

TRY IT! Compute the logical expression for “Is 5 equal to 4?” and “Is 2 smaller than 3?”

Logical operators are operations between two logical expressions that, for the sake of discussion, we call P and Q. The fundamental logical operators we will use herein are AND, OR, and NOT, which in MATLAB are denoted by &&, , and ∼, respectively. There are other logical operators, but they are equivalent to combinations of these three operators. P AND Q is true only if P and Q are both true. P OR Q is true if either P or Q is true or if both P and Q are true. It is important to note that OR in MATLAB is “inclusive” OR, meaning it is true if both P and Q are true. In contrast, “exclusive” OR or XOR is true if either P or Q is true but false if both P and Q are true. If P is true, then NOT P is false, and if P is false, then NOT P is true. The truth table of a logical operator or expression gives the result of every truth combination of P and Q. The truth tables for AND and OR are given in Figure 1.2.

TRY IT! Assuming P is true, use MATLAB to determine if the expression (P AND NOT(Q)) OR (P AND Q) is always true regardless of whether or not Q is true. Logically, can you see why this is the case? First, assume Q is true:

1.3 Logical Expressions and Operators

11

Now assume Q is false:

Just as with arithmetic operators, logical operators have an order of operations relative to each other and in relation to arithmetic operators. All arithmetic operations will be executed before comparison operations, which will be executed before logical operations. Parentheses can be used to change the order of operations. TRY IT! Compute (1 + 3) > (2 + 5).

TIP! Even when the order of operations is known, it is usually helpful for you and those reading your code to use parentheses to make your intentions clearer. In the preceding example (1 + 3) > (2 + 5) is clearer than 1 + 3 > 2 + 5.

WARNING! In MATLAB’s implementation of logic, 1 is used to denote true and 0 for false. However, 1 and 0 are still numbers. Therefore, MATLAB will allow abuses such as » (3>2) + (5>4), which will resolve to 2.

WARNING! Although in formal logic, 1 is used to denote true and 0 to denote false, MATLAB slightly abuses notation and it will take any number not equal to 0 to mean true when used in a logical operation. For example, 3 && 1 will compute to true. Do not utilize this feature of MATLAB. Always use 1 to denote a true statement.

TRY IT! A fortnight is a length of time consisting of 14 days. Use a logical expression to determine if there are more than 100,000 seconds in a fortnight.

12

CHAPTER 1 MATLAB® Basics

Summary 1. You can interact with MATLAB through the MATLAB environment. 2. MATLAB can be used as a calculator. It has all the functions and arithmetic operations commonly used with a scientific calculator. 3. You can also use MATLAB to perform logical operations.

Vocabulary AND arithmetic operation arithmetic operator command window command prompt command history window comparison operator

current directory current directory window execute help function logical expression logical operator MATLAB environment

mathematic expression NOT order of operations OR truth table workspace window

Functions and Operators + ∗ / ˆ () > >= < <=

∼= == && || ∼ ans pi sin cos exp

log log10 help format short format long format bank NaN Inf i

Problems 1. Remove the command history window from the MATLAB environment and then retrieve it. 2. Resize the command prompt so that it takes up less than half of the total MATLAB environment space.

Problems

13

3. Change the background of the MATLAB environment to black and the font color to orange. 4. Change the current directory to any folder other than the current default working directory, and then change it back to the default directory. 5. Type » travel into the command prompt. This program tries to solve the Traveling Salesman Problem. 6. Type » filterguitar into the command prompt. This program simulates the sound of a guitar using mathematical and computational methods. 7. Type » lorenz into the command prompt. The Lorenz Attractor is a mathematical model originally formulated to simulate atmospheric weather patterns. However, it has some surprising results that eventually led to the field of Chaos Theory. This program displays the simulation results for different initial conditions. 8. Compute the area of a triangle with base 10 and height 12. Recall that the area of a triangle is half the base times the height. 9. Compute the surface area and volume of a cylinder with radius 5 and height 3. 10. Compute the slope between the points (3, 4) and (5, 9). Recall that the slope between points 1 (x1 , y1 ) and (x2 , y2 ) is xy22 −y −x1 . 11. Compute the distance between the points (3, 4) and (5, 9). Recall that the distance between  points in two dimensions is (x2 − x1 )2 + (y2 − y1 )2 . 12. Use MATLAB’s factorial function to compute 6! 13. A year is considered to be 365 days long. However, a more exact figure is 365.24 days. As a consequence, if we held to the standard 365-day year, we would gradually lose that fraction of the day over time, and seasons and other astronomical events would not occur as expected. A leap year is a year that has an extra day, February 29, to keep the timescale on track. Leap years occur on years that are exactly divisible by 4, unless it is exactly divisible by 100, unless it is divisible by 400. For example, the year 2004 is a leap year, the year 1900 is not a leap year, and the year 2000 is a leap year. Compute the number of leap years between the years 1500 and 2010. 14. A very powerful approximation for π was developed by a brilliant mathematician named Srinivasa Ramanujan. The approximation is the following: √ N 2 2  (4k)!(1103 + 26390k) 1 ≈ . π 9801 (k!)4 3964k k=0

Use Ramanujan’s formula for N = 0 and N = 1 to approximate π . Be sure to use format long. Compare your approximation with MATLAB’s stored value for pi. Hint: 0! = 1 by definition. (−x) 15. The hyperbolic sin or sinh is defined in terms of exponentials as sinh (x) = exp (x)−exp . 2 Compute sinh for x = 2 using exponentials. Verify that the result is indeed the hyperbolic sin using MATLAB’s built-in function sinh. 16. Verify that sin2 (x) + cos2 (x) = 1 for x = π, π2 , π4 , π6 . Use format long. 17. Call the help function for the function sind. Use sind to compute the sin 87◦ .

14

CHAPTER 1 MATLAB® Basics

18. Write a MATLAB statement that generates the following error: “Undefined function or method ‘sni’ for input arguments of type ‘double’.” Hint: sni is a misspelling of the function sin. 19. Write a MATLAB statement that generates the following error: “Not enough input arguments.” Hint: Input arguments refers to the input of a function (any function); for example, the input in sin(pi/2) is pi/2. 20. Write a MATLAB statement that generates the following error: “Expression or statement is incorrect–possibly unbalanced (, {, or [.” 21. If P is a logical expression, the law of noncontradiction states that P AND (NOT P) is always false. Verify this for P true and P false. 22. Let P and Q be logical expressions. De Morgan’s rule states that NOT (P OR Q) = (NOT P) AND (NOT Q) and NOT (P AND Q) = (NOT P) OR (NOT Q). Generate the truth tables for each statement to show that De Morgan’s rule is always true. 23. Under what conditions for P and Q is (P AND Q) OR (P AND (NOT Q)) false? 24. Construct an equivalent logical expression for OR using only AND and NOT. 25. Construct an equivalent logical expression for AND using only OR and NOT. 26. The logical operator XOR has the following truth table: Construct an equivalent logical expression for XOR using only AND, OR, and NOT that has the same truth table (see Figure 1.3).

1

Q

0

1

0

1

0

1

0

P

FIGURE 1.3 XOR Truth table.

27. Do the following calculation at the MATLAB command prompt. Give answers accurate to 16 digits. e2 sin π/6 + loge (3) cos π/9 − 53

Problems

15

28. Do the following logical and comparison operations at the MATLAB command prompt. You may assume that P and Q are logical expressions. For P = 1 and Q = 1: Compute NOT(P) AND NOT(Q). For a = 10 and b = 25: Compute (a < b) AND (a == b).