Chapter 3
IN THIS CHAPTER
Performing basic and more complex calculations
Interacting with variables
Using MATLAB functions
Overcoming errors
You can interact with MATLAB in a lot of ways, and you’ll experience quite a few of them as the book progresses. However, it pays to start out slowly to build your skills. This chapter presents an overview of the sorts of things you can do with MATLAB. Use this chapter to get started with a product that can really perform complex tasks with aplomb.
Although you probably won’t spend a lot of time using MATLAB as a calculator for even complex calculations, you can do so. Rather than view this kind of use as a waste of time, however, view it as a means of practicing as well as experimentation. Sometimes playing with a product produces unexpected outcomes that can help you in your daily work. To that end, this chapter introduces you to MATLAB through the use of direct calculation entries.
Another type of interaction with MATLAB covered in this chapter occurs through variables. Think of a variable as a kind of storage box. You put data into a variable so that you can store that data for a while. Later, when you need the data again, you take it out of the variable, do something with it, and put it back in again. Variables have nothing mystical or difficult about them; in fact, you use variables all the time in real life. For example, you could view your refrigerator as a kind of variable. You put the bag of apples inside to store them for a short time, take the bag out to remove an apple to eat, and put the rest of the bag back into the refrigerator (minus one apple). The point is that developers make a big deal out of fancy terms (that you unfortunately also need to use in order to talk with them), but in reality there isn’t anything odd about them. You get a fuller explanation of variables as part of this chapter.
In the process of interacting with MATLAB, you’ll make mistakes. Of course, everyone makes mistakes. MATLAB won’t blow up if you make a mistake, and your computer won’t up and run away. Mistakes are part of the learning process, so you need to embrace them. In fact, most of the greatest people in history made a ton of mistakes (see https://www.lifehack.org/articles/communication/10-famous-failures-that-will-inspire-you-success.html). This book assumes that you’re going to make mistakes, so part of this chapter discusses how to recover from them. Knowing how to recover means that you don’t have to worry about making a mistake, because you can always start fresh.
Using MATLAB as a Calculator
MATLAB performs math tasks incredibly well. Sometimes people get so caught up in “what else” an application can do that they miss the most interesting facts that are staring them right in the face. The following sections help you understand MATLAB as a calculator so that you can use it for experimentation purposes.
Entering information at the prompt
References to using the prompt appear a few times in previous chapters, but those chapters don’t fully explain it. The prompt is that place where you type formulas, commands, or functions or perform tasks using MATLAB. It appears in the Command Window. Normally, the prompt appears as two greater-than signs (>>). However, when working with some versions of MATLAB, you might see EDU>> (for the student version) or Trial>> (for the trial version) instead. No matter what you see as a prompt, you use it to know where to type the information described in this book.
Chapter 2 shows you how to use something called the userpath() function to alter the permanent path that MATLAB uses when starting up. In this chapter, you discover a useful command known as clc. Try it now: Type clc and press Enter at the MATLAB prompt. If the Command Window contains any information, MATLAB clears it for you.
The userpath() function is called a function because it uses parentheses to hold the data — also called arguments — that you send to MATLAB. The clc command is a command because you don’t use parentheses with it. Whether something is a function or a command depends on how you use it. The usage is called the function or command syntax (the grammar used to tell MATLAB what tasks to perform). It’s possible to use userpath() in either Function or Command form. To avoid confusion, the book usually relies on function syntax when you need to provide arguments, and command syntax when you don’t. So, when you see parentheses, you should also expect to provide input with the function call (the act of typing the function and associated arguments, and then pressing Enter).
MATLAB is also case sensitive. That sounds dangerous, but all it really means is that CLC is different from Clc, which is also different from clc. Type CLC and press Enter at the MATLAB prompt. You see an error message like the one shown in Figure 3-1. (MATLAB will also suggest the correct command, clc, but ignore the advice for right now by highlighting clc and pressing Delete, or by simply pressing Esc.) Next, type Clc and press Enter at the MATLAB prompt. This time, you see the same error because you made the “same” mistake — at least in the eyes of MATLAB. If you see this error message, don’t become confused simply because MATLAB didn’t provide a clear response to what you typed — just retype the command, being sure to type the command exactly as written.
FIGURE 3-1: MATLAB is case sensitive, so CLC, Clc, and clc all mean different things.
Notice also the “Did you mean:” text that appears after the error message. Normally, MATLAB tries to help you fix any errors. In some cases, MATLAB can’t figure out what’s wrong, so it won’t provide any alternatives for you. In other cases, MATLAB provides an alternative, so you need to check the prompt to determine whether help is available. Because MATLAB was able to provide the correct command in this case, simply press Enter to clear the Command Window.
Look in the Command History window. Notice that a red line appears next to each of the errant commands you typed. These red lines tell you when you shouldn’t use a command or function again because it produced an error the first time. You should also avoid adding errant commands and functions to any scripts you create.
Entering a formula
To enter a formula, you simply type it. For example, if you type 2 + 2 and press Enter, you get an answer of 4. Likewise, if you type 2 * pi * 6378.1 and press Enter, you get the circumference of the earth in km (see https://nssdc.gsfc.nasa.gov/planetary/factsheet/earthfact.html for a list of Earth statistics, including radius). The second formula uses a predefined constant, pi, which equals 3.1416. MATLAB actually defines a number of predefined constants that you can use when entering a formula:
· ans: Contains the most recent temporary answer. MATLAB creates this special temporary variable for you when you don’t provide a variable of your own.
· eps: Specifies the accuracy of the floating-point precision (epsilon), which defaults to 2.2204e-16.
· i: Contains an imaginary number, which defaults to 0.0000 + 1.0000i.
· Inf: Defines a value of infinity, which is any number divided by 0, such as 1 / 0.
· NaN: Specifies that the numerical result isn’t defined (Not a Number).
· pi: Contains the value of pi, which is 3.1416 when you view it onscreen. Internally, MATLAB stores the value to 15 decimal places so that you’re assured of accuracy.
Whenever you type a formula and press Enter, you get an output that specifies the value of ans, which is a temporary value that holds the answer to your question. For example, try typing 2 * pi * 6378.1 and pressing Enter. You see the circumference of the Earth, 4.0075e+04 km.
Copying and pasting formulas
With MATLAB, you can copy and paste formulas that you create into other documents (such as a script or function file, or to another application). To begin, you highlight the information you want to copy. Use one of these methods to copy the text after you highlight it:
· Click Copy on the Quick Access Toolbar (QAT).
· Right-click the highlighted text and choose Copy from the context menu.
· Rely on a platform-specific method of copying the text, such as pressing Ctrl+C on Windows.
UNDERSTANDING INTEGER AND FLOATING-POINT VALUES
Throughout the book, you see the terms integer and floating point. These two terms describe kinds of numbers. When most people look at 3 and 3.0, they see the same number: the value three. The computer, however, sees two different numbers. The first is an integer — a number without a decimal portion. The second is a floating-point value — a number that has a decimal portion, even if it’s a whole number.
You see these two terms often in this book because the computer works with and stores integer values differently from floating-point values. How the computer interacts differently with them is not important — you just need to know that it does. MATLAB does a great job of hiding the differences from view unless the difference becomes important for some reason, such as when you want to perform integer math — in which you want to work with only whole numbers. For example, 4 divided by 3 is equal to 1 with a remainder of 1 when performing integer math.
Humans also don’t pay much attention to the size of a number. Again, the computer must do so because it has to allocate memory to hold the number — and larger numbers require more memory. So, not only do you need to consider the kind of number but also the size of the number when performing some tasks.
Finally, the computer must also consider whether a number has a sign associated with it. The sign takes up part of the memory used to store the number. If you don’t need to store a sign, the computer can use that memory to store additional number information. With all these points in mind, here are the kinds of numbers that MATLAB understands:
· double: 64-bit floating-point double precision
· single: 32-bit floating-point double precision
· int8: 8-bit signed integer
· int16: 16-bit signed integer
· int32: 32-bit signed integer
· int64: 64-bit signed integer
· uint8: 8-bit unsigned integer
· uint16: 16-bit unsigned integer
· uint32: 32-bit unsigned integer
· uint64: 64-bit unsigned integer
Sometimes MATLAB won’t know what you mean when you type 3. A value of 3 could be any kind of number. (MATLAB defaults to assuming that all values are doubles unless you specify otherwise.) To specify the kind of number you mean, you enter the type name and place the value in parentheses. For example, double(3) is a 64-bit floating-point number, but int32(3) is a 32-bit signed integer form of the same number.
When you have the text on the Clipboard, you can paste it wherever you want. If you want to paste it somewhere in MATLAB, click wherever you want to put the text, such as after the prompt. Use one of these methods to paste the text:
· Click Paste on the QAT.
· Right-click the insertion point and choose Paste from the context menu.
· Rely on a platform-specific method of pasting text, such as pressing Ctrl+V in Windows.
Changing the Command Window formatting
The Command Window provides the means necessary to change the output formatting. For example, if you don’t want the extra space between lines that MATLAB provides by default, you can type format compact and press Enter to get rid of it. In fact, try typing that command now. When you type format compact and press Enter, you don’t see any output. However, the next formula you type shows the difference. Type 2 + 2 and press Enter. You see that the extra spaces between lines are gone, as shown in Figure 3-2.
FIGURE 3-2: Modify the appearance of the Command Window using format commands.
MATLAB provides a number of format commands. Each of them begins with the keyword format, followed by an additional instruction. The numeric format instructions, such as long and shortg, control presentation and the number of decimals when there is a decimal portion to display. (Whole numbers are displayed as whole numbers, rather than as a whole number with zeroes in the decimal portion.) When you type format by itself and press Enter, the formatting returns to the default setting. Here is a list of the instructions you can type:
· short: All floating-point output has at least one whole number, a decimal point, and four decimal values, such as 4.2000.
· long: All floating-point output has at least one whole number, a decimal point, and 15 decimal values, such as 4.200000000000000.
· shorte (default): All floating-point output uses exponential format with four decimal places, such as 4.2000e+00.
· longe: All floating-point output uses exponential format with 15 decimal places, such as 4.200000000000000e+00.
· shortg: All output uses a short general format, such as 4.2, with five digits of space.
· long: All output uses a long general format, such as 4.2, with 15 digits of space.
· shorteng: All floating-point output uses exponential format with four decimal places and powers in groups of three, such as 4.2000e+000.
· longeng: All floating-point output uses exponential format with 14 decimal places and powers in groups of three, such as 4.20000000000000e+000.
· hex: All output is in hexadecimal format, such as 4010cccccccccccd.
· +: All output is evaluated for positive or negative values, so that the result contains just a + or – sign, such as + when using the formula 2 * 2.1.
· bank: All output provides two decimal places, even for integer calculations, such as 4.20.
· rat: All output is presented as a ratio of small integers, such as 21/5 for 4.2.
· compact: All output appears in single-spaced format.
· loose: All output appears in double-spaced format.
Suppressing Command Window output
When performing most experiments, you want to see the result of your actions. However, sometimes you really don’t want to keep seeing the results in the Command Window when you can just as easily look in the Workspace window for the result. In these cases, you can follow a command with a semicolon (;), and the Command Window output is suppressed. For example, try typing 2 + 2; and pressing Enter (note the semicolon at the end of the command). You see output in the Workspace window, but not the Command Window.
This technique is often used when you have a complex set of formulas to type and you don’t want to see the intermediate results, or when working with large matrices. Of course, you also want to use this approach when you create scripts so that the script user isn’t bombarded by the results that will appear as the script runs. Anytime you stop using the semicolon at the end of the command, you start seeing the results again.
Understanding the MATLAB Math Syntax
The MATLAB syntax is a set of rules that you use to tell MATLAB what to do. It’s akin to learning another human language, except that the MATLAB syntax is significantly simpler than any human language. In order to communicate with MATLAB, you must understand its language, which is essentially a form of math. Because you already know math rules, you already know many MATLAB rules as well. The following sections get you started with the basics that you use to build an understanding of the MATLAB language. You may be surprised to find that you already know some of these rules, and other rules are simply extensions of those rules.
Adding, subtracting, multiplying, and dividing
MATLAB is a math-based language, so it pays to review the basic rules for telling MATLAB how to perform basic math tasks. Of course, MATLAB performs the basic math functions:
· + or plus(): Adds two numbers. For example, you can use 3 + 4 or plus(3, 4) to obtain a result of 7.
· – or minus(): Subtracts two numbers. For example, you can use 3 – 4 or minus(3, 4) to obtain a result of –1.
· * or times(): Multiplies two numbers. For example, you can use 3 * 4 or times(3, 4) to obtain a result of 12.
· / or rdivide(): Performs right division, which is the form of division you likely learned in school. For example, you can use 3 / 4 or rdivide(3, 4) to obtain a result of 0.75.
· \ or ldivide(): Performs left division, which is also called “goes into” or, as you learned in third grade, “guzinta.” You know (say this out loud), 5 “guzinta” 5 once, 5 “guzinta” 10 twice, 5 “guzinta” 15 three times, and so on. For example, you can use 3 \ 4 or ldivide(3, 4) to obtain a result of 1.3333.
Most MATLAB operators are binary, which means that they work on two values. For example, 3 + 4 has two values: 3 and 4. However, some operators are unary, which means that they work on just one value. Here are the basic unary operators:
· + or uplus(): Returns the unmodified content of a value or variable. For example, +1 or uplus(1) is still equal to 1.
· – or uminus(): Returns the negated content of a value or variable. For example, –1 or uminus(1) returns –1. However, –1 or uminus(–1) returns 1 (the negative of a negative is a positive).
In some cases, you don’t want a floating-point result from division. To perform integer division, you have to use special functions — you can’t just use operators for the simple reason that no operators are associated with these math tasks. Here are the functions associated with integer math:
· idivide(): Performs integer division. You supply two values or variables as input, along with an optional modifier that tells MATLAB how to perform rounding.
To use the idivide() function, you must specify that at least one of the input values is an integer (see the “Understanding integer and floating-point values” sidebar, earlier in this chapter, for details). For example, idivide(int32(5), int32(3)) provides an output of 1. (Note that idivide(int32(5), 3) also works because the first argument is an int32.) Here is a list of the modifiers that you use to provide different rounding effects:
· ceil: Rounds toward positive infinity. For example, idivide(int32(5), int32(3), 'ceil') produces an output of 2, and idivide(int32(5), int32(–3), 'ceil') produces an output of –1.
· fix: Rounds toward zero. For example, idivide(int32(5), int32(3), 'fix') produces an output of 1, and idivide(int32(5), int32(–3), 'fix') produces an output of –1.
· floor: Rounds toward negative infinity. For example, idivide(int32(5), int32(3), 'floor') produces an output of 1, and idivide(int32(5), int32(–3), 'floor') produces a result of –2.
· round: Rounds to the nearest integer. For example, idivide(int32(5), int32(3), 'round') produces an output of 2, and idivide(int32(5), int32(–3), 'round') produces an output of –2. When the result has decimal portion of .5, round will round the value up, rather than down, so idivide(int32(5), int32(2), 'round') produces an output of 3.
· mod(): Obtains the modulus after division. For example, mod(5, 3) produces an output of 2, and mod(5, –3) produces an output of –1.
· rem(): Obtains the remainder after division. For example, rem(5, 3) produces an output of 2, and rem(5, –3) produces an output of 2. Even though the second example has a negative number as the second argument, the remainder is still positive. However, rem(-5, 3) produces an output of -2 because the first argument is negative.
Rounding can be an important feature of an application because it determines the approximate values the user sees. You can round any formula that you want to produce an integer output. Here are the rounding functions:
· ceil(): Rounds toward positive infinity. For example, ceil(5 / 3) produces an output of 2, and ceil(5 / –3) produces an output of –1.
· fix(): Rounds toward zero. For example, fix(5 / 3) produces an output of 1, and fix(5 / –3) produces an output of –1.
· floor(): Rounds toward negative infinity. For example, floor(5 / 3) produces an output of 1, and floor(5 / –3) produces an output of –2.
· round(): Rounds toward nearest integer. For example, round(5 / 3) produces an output of 2, and round(5 / –3) produces an output of –2. A result with a decimal portion of precisely .5 will round up, rather than down, so round(2.5) outputs a value of 3.
Working with exponents
You use the caret (^) to raise a number to a particular power. MATLAB can handle negative, fractional, and complex number bases as exponents. Here are some examples of exponents:
· 10^3 = 1000
· 2^10 = 1024
· 2.5^2.5 = 9.8821
· 2^-4 = 0.0625
· 2^i = 0.7692 + 0.6390i
· i^i = 0.2079
USING THE LETTER E (OR E) FOR SCIENTIFIC NOTATION
In the early days of computing, a display would use seven Light Emitting Diode (LED), or Liquid Crystal Display (LCD) segments to display numbers by turning particular segments on or off. Even today, many watches and clocks use this technique. The following figure shows how a seven-segment display works.
When designers made calculators that displayed scientific notation (see https://www.mathsisfun.com/numbers/scientific-notation.html for an explanation of scientific notation), they thought of the letter E, which reminds users that what follows is an exponent. They could also implement E using a seven-segment display, as shown here:
Then designers got lazy and instead of letting uppercase E mean scientific notation, they also let a lowercase e mean the same thing. In our modern age, designers can use all the pixels that various screens now employ to display the information without using the letter E. However, using E or e caught on, so now we have to use one of them. In addition, seven-segment displays are still commonly used in calculators, watches, clocks, and other devices.
Organizing Your Storage Locker
Computers contain memory, much as your own brain contains memory. The computer’s memory stores information that you create using MATLAB. Looking at memory as a kind of storage locker can be helpful. You open the door, put something inside, and then close the door until you need the item again. When that happens, you simply open the door and take the item out. The idea of memory doesn’t have to be complex or difficult to understand.
Whenever you tell MATLAB to store something in memory, you’re using a variable. Developers use the term variable to indicate that the content of the memory isn’t stable — it can change. The following sections tell you more about the MATLAB storage lockers called variables.
Using ans — the default storage locker
MATLAB always needs a place to store the output of any calculation you perform. For example, when you type 2 + 2 and press Enter, the output tells you that the value is 4. However, it more specifically tells you that ans = 4. MATLAB uses ans as a storage locker when you don’t specify a specific storage locker to use.
MATLAB uses ans as a temporary storage locker. The content lasts only as long as you keep MATLAB open and you don’t perform another calculation that requires ans to hold the output. If you need the result from a calculation for additional tasks, you must store the result in another variable.
If you discover that you need to save the value of ans after performing the calculation, you can still save it. Right-click ans in the Workspace window and choose Rename from the context menu. The ans entry will turn into a text box, where you type the new name you want to use for the storage box. Press Enter. The ans entry is now available for another calculation.
Creating your own storage lockers
Whenever you need to use the result of a calculation in future calculations, you must create your own storage locker to hold the information; using the ans temporary variable just won’t work unless you rename it. Fortunately, creating your own variables is straightforward. The following sections help you create variables that you can use for storing any MATLAB information you want.
Defining a valid variable name
A MATLAB variable name has certain requirements, just as naming other kinds of things must meet specific requirements. For one thing, you can’t use a MATLAB keyword like end or break as a variable name. Here are the rules for creating a MATLAB variable:
· Start with a letter.
· Add:
· Letters
· Digits
· Underscores
With this in mind, naming a variable 7Heaven doesn’t work because this particular variable name begins with a number — and variables must begin with a letter. Likewise, Doug'sStuff doesn’t work as a variable name because the apostrophe (') isn’t allowed as part of a variable name. However, all the following variable names do work:
· MyVariable
· My_Variable
· My7Joys
In each case, the variable name begins with a letter and is followed by a letter, digit, or underscore. If you violate any of these rules, you see an error message similar to this one:
Error: Unexpected MATLAB expression.
Always make variable names meaningful. Even though a variable named x is easy to type, remembering what x contains isn’t so easy. A name such as CosOutput is much easier to remember because it has meaning. At least you know that it contains the output from a cosine calculation. The more meaningful you make the name, the easier it will be for you to later determine what a calculation does.
To create your own variable, type the variable name, an equal sign, and the value you want to assign to that variable. For example, to create a variable called MyName and assign it a value of Amy, you type MyName = 'Amy' and press Enter. (The single quotes show that Amy is a value [data], rather than another variable with the name of Amy.)
Understanding that variables are case sensitive
The “Entering information at the prompt” section, earlier in this chapter, discusses the need to type command and function names precisely as described in the MATLAB documentation because MATLAB is case sensitive. Variable names are also case sensitive, and this is one of the ways in which many users make mistakes when creating a script. The variable myVariable is different from MyVariable because the case is different.
Avoiding existing variable names
Avoiding the use of existing MATLAB names such as pi, i, j, sin, cos, log, and ans is essential. If you don’t know whether a particular name is in use, you can type exist('variable_name') and press Enter. Try it now with pi. Type exist('pi') and press Enter. You see an output of 5, which means that the variable is in use. Now, type exist('MyVariable') and press Enter. The output of 0 means that the variable doesn’t exist.
MATLAB lets you create case-sensitive variations of existing variables. For example, type Ans = 'Hello' and press Enter. You see that the Workspace window now displays two variables, ans and Ans. Using a variable with the same name but different capitalization as an existing MATLAB variable will cause you problems. You’re better off to simply avoid any existing term no matter how you capitalize it.
Operating MATLAB as More Than a Calculator
It’s time to take your first steps beyond using MATLAB as a simple calculator. The following sections help you understand some of the MATLAB functions that you eventually use to perform complex tasks.
Learning the truth
Determining whether something is true is an important part of performing most tasks. You determine the truth value of the information you receive almost automatically thousands of times a day. Computers can perform comparisons and report whether something is true (it does compare) or false (it doesn’t compare). A man named George Boole (see https://plato.stanford.edu/entries/boole/) created a method for quantifying the truth value of information using Boolean logic.
The basic idea is to ask the computer to perform a comparison of two variables. Depending on the values in those variables, the computer will say that it’s either true that they compare or false that they compare. Table 3-1 spells out how Boolean logic works within MATLAB (where an output value of 1 means that the statement is true and an output value of 0 means that the statement is false).
It’s essential to remember that one equal sign (=) is an assignment operator. It assigns the value you provide to the variable. Two equal signs (==) is an equality operator. This operator determines whether two variables contain the same value.
Using the built-in functions
Previous sections of this chapter introduce you to a number of MATLAB functions, but you’ve barely scratched the function surface. MATLAB has a lot of other functions, such as sin(), cos(), tan(), asin(), acos(), atan(), log(), and exp(). Many of these functions appear in other chapters of the book.
TABLE 3-1 Relational Operators
Meaning |
Operator |
Example |
Less than |
A < B |
A=2; B=3; A<b< p=""></b<> ans = 1 |
Less than or equal to |
A <= B |
A=2; B=3; A<=B ans = 1 |
Equal |
A == B |
A=2; B=3; A==B ans = 0 |
Greater than or equal to |
A >= B |
A=2; B=3; A>=B ans = 0 |
Greater than |
A > B |
A=2; B=3; A>B ans = 0 |
Not equal |
A ~= B |
A=2; B=3; A~=B ans = 1 |
For an exhaustive list of functions, go to Appendix A or see https://www.mathworks.com/help/matlab/matlab_prog/function-summary-1.html. Yes, there really are that many. The site has brief descriptions of each function. Also, you can get additional information by using help('function_name'). Try it now. Type help('sin') and press Enter. You see output similar to that shown in Figure 3-3.
FIGURE 3-3: MATLAB makes it easy for you to learn more about functions you need.
Notice that the help screen contains links. Click any link to receive additional information about that topic.
Accessing the function browser
With all the functions that MATLAB provides, you might think it’s impossible to discover what they are without a lot of memorization. Fortunately, help is closer than you might think. Look carefully at the Command Window and you see an fx symbol in the border next to the prompt. Click the down arrow under the symbol and you see the dialog box shown in Figure 3-4. The official name of this dialog box is the Function Browser, and you use it to browse through categories of functions to track down the function you want.
FIGURE 3-4: Use the Function Browser to find what you need quickly.
You can also access the Function Browser using these techniques:
· Right-click the Command Window and choose Function Browser from the context menu.
· Press Shift+F1.
Now that you have a better idea of what the Function Browser is, it’s time to look at it in more detail. The following sections provide additional information on using the Function Browser.
Looking through the Function categories
The Function Browser is designed for you to easily drill down into a topic until you find precisely what you need. For example, when you click the Mathematics folder, you see a number of subcategories, such as Elementary Math, Linear Algebra, and Interpolation. When you click Elementary Math, you see yet more subcategories, such as Arithmetic, Trigonometry, and Polynomials. When you finally get to a list of functions, you see the fx symbol next to the entries, as shown in Figure 3-4.
Searching for a particular function
Sometimes you already have a good idea of what you want to find. In such a case, you can type all or part of a function name in the search bar at the top of the Function Browser window. For example, type sin (without pressing Enter) in the search field to see all the functions that contain sin in their name or description, such as sine.
Recovering from Mistakes
Everyone makes mistakes. You might think that experts don’t make mistakes, but any expert who says so definitely isn’t an expert. As Nobel Prize–winning physicist Niels Bohr said, “An expert is a person who has made all the mistakes that can be made in a very narrow field” (see https://www.goodreads.com/quotes/5-an-expert-is-a-person-who-has-made-all-the). Making mistakes is part of the learning process. It’s also part of the discovery process. If you want to do anything important with MATLAB, you’re going to make mistakes. The following sections help you understand what to do when mistakes happen.
Understanding the MATLAB error messages
MATLAB tries to be helpful when you make mistakes. It doesn’t always succeed, and you may not always understand the message, but it does try. In most cases, you see an error message that provides enough information for you to at least get started in finding the mistake. For example, if you try to use the clc command but type it in uppercase, you get
Undefined function or variable 'CLC'.
The error message is enough to get you looking for a solution to the problem, even when the problem isn’t completely clear. In some cases, MATLAB even provides the correct command for you. All you have to do is press Enter, and it executes.
Some errors are a little harder to figure out than others. For example, Figure 3-5 shows what happens when you try to use idivide() without specifying that the inputs are integers.
FIGURE 3-5: Some error messages are a bit complex.
In this case, you can ignore the links and what looks like gobbledygook. Focus on the second line. It tells you that one of the arguments must belong to the integer class, even though the actual message says Not enough input arguments. The Command Window evaluates the expression 5 / 3 and passes the result to idivide. Because that expression creates only a single, idivide is confused because it expects two arguments. When you get past the odd bits of information, you can more easily figure out how to fix the problem.
Stopping MATLAB when it hangs
Most of the time, MATLAB is extremely forgiving. You can make absolutely horrid mistakes, and MATLAB simply provides what it considers a helpful message without destroying anything. However, at times MATLAB has to chew on a bit of code for a while before it discovers the error, such as when you’re working with a really large array. In this case, you can talk to your buddy in the next cubicle, get a cup of coffee and read a good book, or press Ctrl+C to stop MATLAB from going any further.
Pressing Ctrl+C always stops MATLAB from performing any additional processing. It’s important that you don’t use this option unless you really need to do so because MATLAB truly does stop right in the middle of what it’s doing, which means that whatever you were doing is in an uncertain state. It’s good to know that the option exists, though.