Part 5
IN THIS PART …
Installing and using the Symbolic Math Toolbox
Solving problems using algebra and statistics
Performing analysis using linear algebra, calculus, and differential equations
Chapter 19
IN THIS CHAPTER
Using the Symbolic Math Toolbox
Solving algebraic problems
Solving statistical problems
MATLAB is amazing when it comes to helping you solve equations and find roots. Of course, getting the right answer happens only when you know how to ask the right question. Communicating with MATLAB in a manner it understands is an important part of solving the questions you have. This chapter demonstrates how to solve specific kinds of equations and how to find roots. The important thing to consider as you read is how the information creates patterns that you can use to solve your specific algebraic or statistical problem.
In most cases, there are multiple ways to obtain an answer to any question. This chapter demonstrates one method for each kind of equation or root. However, you can find additional solutions online in locations such as MATLAB Answers (https://www.mathworks.com/matlabcentral/answers/). The point is that MATLAB can provide an answer as long as you have a viable means to ask the question.
You don’t have to type the source code for this chapter; in fact, using the downloadable source is a lot easier. You can find the source for this chapter in the \MATLAB2\Chapter19 folder of the downloadable source. When using the downloadable source, you may not be able to work through some of the hands-on examples because the example files will already exist on your system. In this case, you can create an alternative folder, Chapter19a, to hold the results of the hands-on exercises. See the Introduction for details on how to obtain the downloadable source.
Working with the Symbolic Math Toolbox
The Symbolic Math Toolbox immensely reduces the work required to solve equations. In fact, it might almost seem like magic to some people. Of course, no magic is involved — the clever programmers at MathWorks just make it look that way.
However, before you can begin using the Symbolic Math Toolbox to perform amazing feats, you need to have it installed. If you have the student version, the Toolbox is installed by default, and you can skip the first two sections that follow (going right to the “Working with the GUI” section). Otherwise, start with the first section that follows to get your copy of the Symbolic Math Toolbox and install it on your system.
Obtaining your copy of the Symbolic Math Toolbox
You need to obtain either a trial version or a purchased version of the Symbolic Math Toolbox before you can do anything else. (When getting a trial version, you must discuss the download with someone from MATLAB before you can actually download the product or at least go through a rather confusing series of forms.) Check out the product information at https://www.mathworks.com/products/symbolic.html#try-buy and click one of the links in the Try or Buy section of the page. The following steps (with possibly some small changes) assume that you’re using the trial version for installation purposes:
1. Click Download Now.
You see the page shown in Figure 19-1 (or one similar to it), which provides options for identifying yourself and determining whether you actually need a copy of the Symbolic Math Toolbox. For example, college students may already have the required toolbox installed.
2. Provide the required information, select I Agree, and click Submit.
The website will ask you to choose a trial release. Click the button that matches the version of your MATLAB installation. You’re asked to choose a platform: Windows, macOS, or Linux.
3. Click a platform option.
You see a list of trial products.
FIGURE 19-1: Verify the need for the toolbox, then supply the required information.
4. Select the Symbolic Math Toolbox option; then click the Trial Products button that appears near the bottom of the page.
The website shows the products you require when using the product you’ve selected. For example, all the toolboxes require that you have MATLAB installed. You select an option only if you don’t have the product installed on your system already. Otherwise, leave the list cleared. You shouldn’t have to check any of the items if you’ve been working through the book because you already have MATLAB, the only required product for the Symbolic Math Toolbox, installed.
5. Click Continue.
You see an informational page for the product. In the upper-left corner, you also see three buttons: Windows, macOS, and Linux.
6. Click the button that matches your platform.
The product and associated installer will download to your system.
Installing the Symbolic Math Toolbox
By this part of the chapter, you should have a number of files on your hard drive. These files provide everything needed to install the Symbolic Math Toolbox. You have two ways to interact with the files:
· If you were able to use the download agent, you see a dialog box telling you that the download is complete. At this point, you can perform one of these two tasks:
· Select the Start Installer option and click Finish to start the installation process. The Symbolic Math Toolbox installer starts automatically.
· Select the Open Location of the Downloaded Files option and click Finish. You see the location of the files open, and you must double-click the installer file to start the installation process. (The installer file is typically the only executable program in the folder.)
· If you performed the manual download process, you need to find the download location of the files. You must double-click the installer file to start the installation process. (The installer file is typically the only executable program in the folder.)
Windows platform users may see a User Account Control (UAC) dialog box when starting the installer. Click Yes to give the installer permission to install the Symbolic Math Toolbox. Otherwise, the installation will fail.
No matter how you start the installer, eventually you see a MathWorks Product Installer wizard. This wizard asks questions about how to install the toolbox. The following steps help you complete the installation process. Make sure you have no copies of MATLAB open before you begin this process.
1. Enter your email address and click Next.
The wizard asks for your password.
2. Enter your password and click Sign In.
The wizard shows the licensing terms for using the toolbox.
3. Select Yes to accept the licensing agreement; then click Next.
You see the license selection page, shown in Figure 19-2. It’s important to select the correct license, or to enter an activation key, depending on what you have. Select the Self Serve R2020b Trial option only if you don’t have a license or activation key to use.
If you see an error message at this point, it could be because the application can’t access the MathWorks website. Ensure that your firewall will let MATLAB connect to outside networks, restart your copy of MATLAB, and try again.
FIGURE 19-2: Choose the licensing option that best matches your setup.
4. Choose a Licensing option and then click Next.
The wizard asks for confirmation of your identity.
5. Enter the required information and then click Next.
The wizard asks for a destination folder for the toolbox. This folder should match the folder of your MATLAB installation.
6. If necessary (normally it’s not, because the default is correct), supply a destination for the installation and click Next.
At this point, it may appear that the MathWorks Product Installer has frozen. However, the wizard is simply checking all the installation conditions. After performing the required checks, the wizard shows a list of detected products.
7. Select the Select All option and click Next.
You see a list of installation options that include adding a shortcut to the desktop and allowing MATLAB to send usage information to MathWorks.
8. Select the options you want to use and click Next.
You see a list of the installation selections you have made.
9. Click Begin Install.
The wizard performs the required installation tasks. You see a completion page when the process completes.
10. Click Finish.
The installation is complete.
Working with the GUI
When performing tasks with the Symbolic Math Toolbox, you create a Live Script, or possibly a Live Function, as described in Chapters 11 and 12 of the book. The focus when working with the toolbox basics is the sym() function. For example, when you type sym(1/3) and run the code, you see the symbolic version of the code as a symbolic number. You can see how this use of the sym() function works in the Symbolic_Basics.mlx file provided with the downloadable source.
You can also create symbolic variables, such as y = sym('y', [1 5]), and symbolic expressions, such as:
phi = (1 + sqrt(sym(5)))/2;
f = phi^2 - phi – 1
In every case, the Live Script display will show the result of the symbolic expression, as shown in Figure 19-3. Notice that each entry is a neatly formatted version that you could easily use for a report.
FIGURE 19-3: Viewing the Live Script output of the sym() function.
WHERE HAS MuPAD GONE?
Older versions of the Symbolic Math Toolbox provided an app named MuPAD. However, MathWorks removed this app from MATLAB starting with R2020a. The recommendation now is to use Live Script instead. Fortunately, you can update your MuPAD files to their Live Script form by using the instructions found at https://www.mathworks.com/discovery/mupad.html.
Typing a simple command in the Command Window
The essentials of the MATLAB Command Window haven’t changed since you installed the Symbolic Math Toolbox, and you may decide to try things there instead of creating a Live Script. This section shows how to use features such as solve() (which you can also find in the UsingSolve.mlx file). You can get all the details about the Symbolic Math Toolbox functionality at https://www.mathworks.com/help/symbolic/index.html. The details about the new functions that MATLAB can access from the Symbolic Math Toolbox appear at https://www.mathworks.com/help/symbolic/referencelist.html?type=function. The following steps show how to perform the same task using MATLAB at the Command Window:
1. Type syms x y and press Enter.
MATLAB creates two symbolic variables, x and y. You use symbolic variables when working with solve(). When you look in the Workspace window, you see that the variables are actually defined as being symbolic.
2. Type solve(2 * x + 3 * y - 22 == 0) and press Enter.
You see the following output:
ans =
11 - (3*y)/2
This code solves the equation for x in terms of y.
3. Type solve(2 * x + 3 * y - 22 == 0, y) and press Enter.
This time, solve() solves for y rather than x. The output is now:
ans =
22/3 - (2*x)/3
4. Type solve(11 - (3*y)/2) and press Enter.
You now have the value of x, which is 22/3.
5. Type solve(2 * 22/3 + 3 * y - 22 == 0) and press Enter.
The value of y is 22/9. The next step is to test the solution by plugging in both values.
6. Type 2 * 22/3 + 3 * 22/9 - 22 == 0 and press Enter.
You see an output of
ans =
logical
1
The output is now logically equal to 0. Figure 19-4 shows this example in Live Script form.
FIGURE 19-4: Seeing the Command Window steps as a Live Script.
Performing Algebraic Tasks
MATLAB lets you perform a wide range of algebraic tasks even without the Symbolic Math Toolbox installed, but adding the toolbox makes performing the tasks easier. The following sections discuss using the Symbolic Math Toolbox to perform a variety of algebraic tasks. You also discover a few alternatives for performing these tasks.
Differentiating between numeric and symbolic algebra
The essential difference between symbolic and numeric algebra is that the first is used by computer science to explore principles of algebra using symbols in place of values, while the second is used by science to obtain approximations of equations for real-world use. In the “Typing a simple command in the Command Window” section, earlier in this chapter, you type equations to perform symbolic algebra. In that case, you use solve(), which outputs a precise number (which is why you see a value of x that is 22/3). When you want to perform numeric algebra, you use the vpasolve() function instead. (VPA stands for Variable Precision Arithmetic.) The following steps demonstrate how to perform this task (you can also see the Live Script form in UsingVpaSolve.mlx):
1. Type syms x y and press Enter.
Even when performing numeric algebra, you must define the variables before you use them.
2. Type vpasolve(2 * x + 3 * y - 22 == 0, x) and press Enter.
You see the following output:
ans =
11.0 - 1.5*y
The output is simpler this time, but notice that it also relies on floating-point numbers. To ensure precision, symbolic algebra relies on integers or integer fractions. A floating-point number is an approximation in the computer — an integer is precise.
When working with vpasolve(), you must specify which variable to solve for. There is no assumption, and if you don’t provide a variable when working with multiple variables, the output is less than useful. In this case, vpasolve() solves for x.
3. Type vpasolve(11.0 - 1.5*y) and press Enter.
You see the following output:
ans =
7.3333333333333333333333333333333
The output is a floating-point number. You aren’t dealing with a fraction any longer, but the number is also an approximation. You need to note that vpasolve() defaults to providing 32-digit output — a double is 16 digits.
4. Type vpasolve(2 * 7.3333333333333333333333333333333 + 3 * y - 22 == 0) and press Enter.
You see the following output:
ans =
2.4444444444444444444444444444444
Again, the output is a floating-point number. The result is imprecise. However, seeing whether the computer can actually show you how much it’s off might be interesting.
5. Type 2 * 7.3333333333333333333333333333333 + 3 * 2.4444444444444444444444444444444 - 22 and press Enter.
MATLAB likely outputs a value of 0. The point is that the two output values truly aren’t precise values, but the computer lacks the precision to detect just how much of an error exists. Figure 19-5 shows the Live Script output of this example.
FIGURE 19-5: Seeing the algebraic computation as a Live Script.
Solving quadratic equations
There are times when using the Symbolic Math Toolbox makes things easier, but using it isn’t absolutely necessary. This is the case when working with quadratic equations. You actually have a number of ways to solve a quadratic equation, but two straightforward methods exist: solve() and roots().
CONVERTING BETWEEN SYMBOLIC AND NUMERIC DATA
Symbolic and numeric objects aren’t compatible. You can’t directly use one with the other. To make the two coexist, you must perform a conversion. Fortunately, MATLAB makes converting between symbolic and numeric data easy. The following functions perform the conversions for you:
· double(): Converts a symbolic matrix to a numeric form.
· char(): Converts symbolic objects to plain strings.
· int8(): Converts a symbolic matrix into 8-bit signed integers.
· int16(): Converts a symbolic matrix into 16-bit signed integers.
· int32(): Converts a symbolic matrix into 32-bit signed integers.
· int64(): Converts a symbolic matrix into 64-bit signed integers.
· poly2sym(): Converts a polynomial coefficient vector to a symbolic polynomial.
· single(): Converts a symbolic matrix into single-precision floating-point values.
· sym(): Defines new symbolic objects.
· sym2poly(): Converts a symbolic polynomial to a polynomial coefficient vector.
· symfun(): Defines new symbolic functions.
· uint8(): Converts a symbolic matrix into 8-bit unsigned integers.
· uint16(): Converts a symbolic matrix into 16-bit unsigned integers.
· uint32(): Converts a symbolic matrix into 32-bit unsigned integers.
· uint64(): Converts a symbolic matrix into 64-bit unsigned integers.
· vpa(): Performs a conversion between symbolic and numeric output. For example, vpa(22/3) results in an output of 7.3333333333333333333333333333333.
The solve() method is actually easier to understand, so type solve(x^2 + 3*x - 4) and press Enter. This approach finds the roots of the equation, the values of x that make the equation equal zero. You see the following output:
ans =
-4
1
In this case, you work with a typical quadratic equation. The equation is entered directly as part of the solve() input. You don’t necessarily need to use a double equals sign (==); using solve(x^2 + 3*x - 4) results in the same output as solve(x^2 + 3*x - 4 == 0). However, you must remember to add the multiplication operator. Otherwise, the equation looks precisely as you might write it manually.
The roots() approach isn’t quite as easy to understand by just viewing it. Type roots([1 3 -4]) and press Enter. As before, you get the following output:
ans =
-4
1
The outputs are the same. However, when working with roots(), you pass a vector containing just the constants (coefficients) for the equation in a vector. Nothing is wrong with this approach, but six months from now, you may look at the roots() call and not really understand what it does.
Working with cubic and other nonlinear equations
The Symbolic Math Toolbox makes it easy to solve cubic and other nonlinear equations. The example in this section explores the cubic equation, which takes the form of ax^3+bx^2+cx+d=0. Each of the coefficients takes the following values (you can see the Live Script version of this example in SolvingCubic.mlx):
· a=2
· b=-4
· c=-22
· d=24
Now that you have the parameters for the cubic equation, it’s time to solve it. The following steps show you how to solve the problem in the Command Window:
1. Type syms x and press Enter.
MATLAB creates the required symbolic object.
2. Type each of the following coefficients in turn, pressing Enter after each coefficient:
a=2;
b=-4;
c=-22;
d=24;
3. Type Solutions = solve(a*x^3 + b*x^2 + c*x + d == 0) and press Enter.
You see the following output:
Solutions =
-3
1
4
Of course, you can get far fancier than the example shown here, but the example gives you a good starting point. The main thing to consider is the coefficients you use. (If you ever want to check your answers, the Cubic Equation Calculator at http://www.1728.org/cubic.htm can help.)
Understanding interpolation
MATLAB supports a number of types of interpolation, a statistical method that uses related known values to estimate an unknown value. (See https://whatis.techtarget.com/definition/extrapolation-and-interpolation for a description of interpolation.) You can see an overview of support for interpolation at https://www.mathworks.com/help/matlab/interpolation.html. For this section, you work with 1D interpolation using the interp1() function. The following steps show how to perform the task (you can see the Live Script version of this example in SolvingInterpolation.mlx):
1. Type x = [0, 2, 4]; and press Enter.
2. Type y = [0, 2, 8]; and press Enter.
These first two steps create a series of points to use for the interpolation.
3. Type x2 = [0:.1:4]; and press Enter.
At this point, you need to calculate the various forms of interpolation: linear, nearest, spline, and pchip. Steps 4 through 7 take you through this process. (Older versions of MATLAB also had a cubic option that’s been replaced by pchip.)
4. Type y2linear = interp1(x, y, x2); and press Enter.
5. Type y2nearest = interp1(x, y, x2, 'nearest'); and press Enter.
6. Type y2spline = interp1(x, y, x2, 'spline'); and press Enter.
7. Type y2pchip = interp1(x, y, x2, 'pchip'); and press Enter.
At this point, you need to plot each of the interpolations so that you can see them onscreen. Steps 8 through 11 take you through this process.
8. Type plot(x,y,'sk-') and press Enter.
You see a plot of the points, which isn’t really helpful, but it’s the starting point of the answer.
9. Type hold on and press Enter.
The plot will contain several more elements, and you need to put the plot into a hold state so that you can add them without clearing the previous results.
10. Type plot(x2, y2linear, 'g--') and press Enter.
You see the interpolation added to the figure (along with the others as you plot them).
11. Type plot(x2, y2nearest, 'b--') and press Enter.
12. Type plot(x2, y2spline, 'r--') and press Enter.
13. Type plot(x2, y2pchip, 'm--') and press Enter.
14. Type legend('Data','Linear', 'Nearest', 'Spline', 'PCHIP', 'Location', 'West') and press Enter.
You see the result of the various calculations, as shown in Figure 19-6.
15. Type hold off and press Enter.
MATLAB removes the hold on the figure.
FIGURE 19-6: Viewing the results of the interpolation operations.
Working with Statistics
Statistics is an interesting area of math that deals with the collection, organization, analysis, interpretation, and presentation of data. You use it to determine the probability of the next customer buying your new widget instead of the obviously inferior widget offered by your competition. The fact is that modern business couldn’t exist without the use of statistics.
MATLAB provides basic statistical support. However, if your living depends on working with statistics and you find the default MATLAB support a little lacking, you can check out the Statistics and Machine Learning Toolbox at https://www.mathworks.com/products/statistics/ to gain additional functionality. Likewise, if you perform a lot of curve fitting, you may find that the Curve Fitting Toolbox found at https://www.mathworks.com/products/curvefitting/ comes in handy. (Admittedly, you can perform elementary ad hoc curve fitting in the figure window, but it’s usually not sufficient to get the results you want.) The following sections don’t use either the Statistics Toolbox or the Curve Fitting Toolbox for examples — they demonstrate how you can perform these tasks using MATLAB alone.
Understanding descriptive statistics
When working with descriptive statistics, the math quantitatively describes the characteristics of a data collection, such as the largest and smallest values, the mean value of the items, and the average. This form of statistics is commonly used to summarize the data, thus making it easier to understand. MATLAB provides a number of commands that you can use to perform basic statistics tasks. The following steps help you work through some of these tasks (you can see the Live Script version of this example in DescriptiveStatistics.mlx):
1. Type rng('shuffle', 'twister'); and press Enter.
You use the rng() function to initialize the pseudo-random number generator to produce a sequence of pseudo-random numbers. Older versions of MATLAB use other initialization techniques, but you should rely on the rng() function for all new applications.
The first value, shuffle, tells MATLAB to use the current time as a seed value. A seed value determines the starting point for a numeric sequence so that the pattern doesn’t appear to repeat. If you want to exactly repeat the numeric sequence for testing purposes, you should provide a number in place of shuffle.
The second value, twister, is the number generator to use. MATLAB provides a number of these generators so that you can further randomize the numeric sequences you create. The upcoming “Creating pseudo-random numbers” sidebar discusses this issue in more detail.
2. Type w = 100 * rand(1, 100); and press Enter.
This command produces 100 pseudo-random numbers that are uniformly distributed between the values 0 and 1. The numbers are then multiplied by 100 to bring them up to the integer values used in Steps 4 and 5.
3. Type x = 100 * randn(1, 100); and press Enter.
This command produces 100 pseudo-random numbers that are normally distributed. The numbers can be positive or negative, and multiplying by 100 doesn’t necessarily ensure that the numbers are between –100 and 100 (as you see later in the procedure).
4. Type y = randi(100, 1, 100); and press Enter.
This command produces 100 pseudo-random integers (the first argument) that are uniformly distributed between the values of 1 (the second argument) and 100 (the third argument).
5. Type z = randperm(200, 100); and press Enter.
This command produces 100 unique pseudo-random integers between the values of 1 and 200. There is never a repeated number in the sequence, but the 100 values are selected from the range of 1 to 200.
6. Type AllVals = [w; x; y; z]'; and press Enter.
This command creates a 100 x 4 matrix for plotting purposes. Combining the four values lets you create a plot with all four distributions without a lot of extra steps.
7. Type hist(AllVals, 50); and press Enter.
You see a histogram created that contains all four distributions.
8. Type legend('rand', 'randn', 'randi', 'randperm'); and press Enter.
Adding a legend helps you identify each distribution, as shown in Figure 19-7. Notice how the various distributions differ. Only the randn() distribution provides both positive and negative output.
9. Type set(gca, 'XLim', [0, 200]); and press Enter.
Figure 19-8 shows a close-up of the rand(), randi(), and randperm() distributions, which are a little hard to see in Figure 19-7. Notice the relatively even lines for randperm(). The rand() and randi() output has significant spikes.
FIGURE 19-7: The histogram shows the distribution of the various numeric values.
FIGURE 19-8: Zoom in to see the differences in distributions better.
When working with a Live Script, you must place a section break between Steps 8 and 9 to see both versions of the histogram. Otherwise, you see just the version produced by Step 9. Figure 19-9 shows part of the Live Script for this example.
This procedure has demonstrated a few aspects of working with statistics, the most important of which is that choosing the correct function to generate your random numbers is important. When viewing the results of your choices, you can use plots such as the histogram. In addition, don’t forget that you can always modify the appearance of the plot to get a better view of what you have accomplished.
FIGURE 19-9: Use section breaks to allow the display of multiple graph versions.
Of course, you can interact with the vectors in other ways. For example, you can use standard statistical functions on them. (If you have forgotten what some of these terms mean, check out https://anothermathgeek.hubpages.com/hub/How-to-calculate-simple-statistics.) Table 19-1 contains a list of the functions, tells what they do, and provides a short example based on the example in the steps in this section.
Understanding robust statistics
Robust statistics is a form of descriptive statistics in which the extreme values are discarded in favor of analysis with smaller changes and less potential for error. You use robust statistics when you have a potential for error in the extreme values. For example, you might use it when trying to figure out the average height of drivers today compared with those of 1940. However, you wouldn’t use it when building a bridge, because the extreme values are important in this second case. When working with MATLAB without any of the specialized toolkits, the best way to create robust statistics is to simply eliminate the largest and smallest values from a vector.
TABLE 19-1 MATLAB Basic Statistical Functions
Function |
Usage |
Example |
corrcoef() |
Determines the correlation coefficients between members of a matrix. |
corrcoef(AllVals) |
cov() |
Determines the covariance matrix for either a vector or a matrix. |
cov(AllVals) |
max() |
Specifies the largest element in a vector. When working with a matrix, you see the largest element in each row. |
max(w) |
mean() |
Calculates the average or mean value of a vector. When working with a matrix, you see the mean for each row. |
mean(w) |
median() |
Calculates the median value of a vector. When working with a matrix, you see the median for each row. |
median(w) |
min() |
Returns the smallest element in a vector. When working with a matrix, you see the smallest element in each row. |
min(w) |
mode() |
Determines the most frequent value in a vector. When working with a matrix, you see the most frequent value for each row. |
mode(w) |
std() |
Calculates the standard deviation for a vector. When working with a matrix, you see the standard deviation for each row. |
std(w) |
var() |
Determines the variance of a vector. When working with a matrix, you see the variance for each row. |
var(w) |
CREATING PSEUDO-RANDOM NUMBERS
Creating truly random numbers on a computer is impossible without resorting to some really exotic techniques. All random sequences on a computer are generated by algorithms, making them pseudo-random. The numeric sequence has a pattern that eventually repeats itself. Depending on the algorithm used, the sequence can be quite long and, to a human, nearly indistinguishable from a random sequence. However, other computers aren’t fooled, and any computer can eventually detect the repetition of the sequence.
MATLAB provides three methods of making the pseudo-random numbers created by it appear more random. The first is the seed value. Choosing a different starting point in the numeric sequence (which is quite large) means that people are less likely to actually notice any repetition. The second method provides four different distributions: rand() produces a uniform distribution of random numbers; randn() produces a normalized distribution of random numbers; randi() produces a uniform distribution of integers (where only whole numbers are needed); and randperm() produces a random permutation (where each number appears only once). The third method provides a number of randomizing generators (or engines) — essentially different algorithms — to produce the numeric sequence:
· 'combRecursive': Relies on the combined Multiple Recursive Generator (MRG) (see https://www.value-at-risk.net/multiple-recursive-generators/ for details).
· 'multFibonacci': Uses the Multiplicative Lagged Fibonacci Generator (MLFG) variant of the Lagged Fibonacci Generator (LFG) (see https://northstar-www.dartmouth.edu/doc/sprngsv1.0/DOCS/www/paper/node13.html for details).
· 'twister': Relies on the Mersenne Twister algorithm (see http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html for details).
· 'simdTwister': Defines a faster, Single Instruction/Multiple Data (SIMD), version of the 'twister' algorithm (see https://walkingrandomly.com/?p=6502 for details.) You can discover more about SIMD at https://us.fixstars.com/products/opencl/book/OpenCLProgrammingBook/parallel-computing-hardware/.
· 'philox': Relies on the 64-bit, counter-based, Philox algorithm (see https://numpy.org/doc/stable/reference/random/bit_generators/philox.html for details).
· 'threefry': Relies on either a 32-bit or 64-bit counter-based generator (see https://bashtage.github.io/randomgen/bit_generators/threefry.html for details).
You also have access to these legacy generators, but it’s best to use one of the newer versions. Use the rng() function, rather than the rand() function used in the past, to randomize the generators whenever possible (see https://www.mathworks.com/help/matlab/math/updating-your-random-number-generator-syntax.html for details).
· 'v5uniform': Specifies the legacy MATLAB 5.0 uniform generator, which produces the same result as the 'state' option with rand().
· 'v5normal': Specifies the legacy MATLAB 5.0 normal generator, which produces the same result as the 'state' option with randn().
· 'v4': Specifies the legacy MATLAB 4.0 generator, which produces the same result as using the 'seed' option.
The easiest way to find and remove the largest and smallest values is to use the statistical functions found in Table 19-1. For example, to remove the largest value from a vector, a, you use a(a == max(a)) = [];. The max(a) part of the command finds the maximum value in vector a. The index (a == max(a)) tells MATLAB to find the index where the maximum value resides. You then set this element to an empty value, which deletes it.
Removing the smallest value from a vector is almost the same as removing the largest value. However, in this case you use a(a == min(a)) = [];. Notice that the min(a) function has taken the place of max(a).
To verify that the changes are successful, you use the std(), or standard deviation, function. As you remove large and small values, you start to see smaller std() output values.
Employing the Symbolic Math Toolbox for plotting
MATLAB provides access to a wide variety of plotting function, and you see them spread in various places throughout the book, such as in Chapters 6 and 7. The Symbolic Math Toolbox provides another means of plotting, fplot(), that involves using functions. This section shows how to use fplot() to visualize the output of symbolic functions you create (you can see this example in SMTPlot.mlx file).
One of the easiest ways to see fplot() in action is to use one of the built-in MATLAB functions, such as sin(). The simplest version of this plot calls fplot(), as shown here:
syms x
fplot(sin(x))
Of course, you might want to see a particular range of outputs, so you can add them as a second argument: fplot(sin(x), [-pi pi]). If you want, you can plot multiple functions simultaneously. For example, this call, fplot([sin(x), cos(x)], [-pi pi]), produces the output shown in Figure 19-10.
FIGURE 19-10: You can plot multiple functions in a single call to fplot().
You can use all the same line styles, markers, and colors with fplot() that you do when working with other MATLAB plotting functions. Setting these visual elements up using a single call can be time consuming, so the best option is to make one call for each function, as shown here:
fplot(sin(x), [-pi pi], '--g')
hold on
fplot(cos(x), [-pi pi], ':ob')
hold off
It wouldn’t be helpful if you couldn’t create custom functions to work with fplot(). Here’s an example of using a symbolic function:
syms f(x);
f(x) = tan(x);
fplot(f, [0 5])
The limitation on custom functions is that they can have only one input variable. However, you can plot as many custom functions as needed. Here’s another example with two plot custom functions:
syms t1
x = (sin(t1^2));
y = (cos(t1^2));
fplot(x, [0 5], '--+g')
hold on
fplot(y, [0 5], ':*b')
hold off
Another way to plot multiple custom lines is to place the functions in a vector, like this: fplot([x y], [0 5]). However, using this form means that you would have to modify features like line style and markers outside the plotting call.
You can also create parametric curves using fplot(). A parametric curve is one in which the curve defined by an x and a y coordinate equation traces changes in a parameter, so that the curve has direction. Think about a curve that would trace Earth’s orbit around the Sun. The article at http://mathonline.wikidot.com/parametric-curves provides more information about parametric curves. The following code creates a circle:
syms t2
x = (sin(t2^2));
y = (cos(t2^2));
fplot(x,y, [0 5])