Skip to main content

Section 10.3 Challenge Problem

Let’s put this all together in an example in MATLAB. In the script that you have already started, create a new section. If you forgot how to do this, a quick recap of Chapter 8 should help.
Now, Let us consider the function \(f(x)=x^3-6x^2+x-10\) and say that for whatever reason we would like to calculate the value of the function at different values of \(x\text{.}\) Specifically, lets consider evaluating the function at the following values: \(-3,-2,-1,0,1,2,3\text{.}\) Finally, let’s store all of the corresponding values of the evaluated function in a new array called fun.
How can we perform the preceding question in MATLAB? We COULD type out the correct mathematical operation for every value like this:
fun(1) = (-3)^3 - 6*(-3)^2 + (-3) - 10
fun(2) = (-2)^3 - 6*(-2)^2 + (-2) - 10
… etc etc… but please DO NOT DO THIS!
Stop and Think
The above β€œsolution” would be wasting the power of MATLAB and would be extremely tedious. Instead, think. about what we have learned and how it relates to this problem. Do not continue reading until you have some ideas about how to proceed.

Example 10.3.1. Challenge Problem.

Here is an interactive code box that functions identically to the MATLAB command window.
I hope you didn’t skip your brain workout. It is important! I hope that you have some inclination that we can use arrays and array mathematics to solve this problem quickly.
Solution
  1. Define the \(x\) array in MATLAB. Notice that the values of \(x\) are from –3 to 3 and are equally spaced by 1. Sound familiar? Sure! Just type in x =[-3:3] to define that vector.
  2. To solve for the function at every different value of \(x\text{,}\) you just need to perform the mathematical operations onto the array of \(x\) like this:
    fun = x.^3 - 6*x.^2 + x - 10;
When you are done, the section in your script file should look similar to example 10.3.2 below.

Example 10.3.2. Challenge Problem Solution.

Here is an interactive code box that functions identically to the MATLAB command window.
For this question, let’s consider the preceding example, but this time, redefine x to be from x = 1 to x=999 equally spaced by 1. To accomplish this, you should only have to modify two numbers in your script. After running it, you have now created a fun array with 1000 entries!

Checkpoint 10.3.3. Beauty of MATLAB.

That is the beauty of MATLAB! You can change one or two numbers, and re-run your script without having to do much work. If you struggled with the question above, it is ok! If you are struggling then you are learning! But you also need to figure out a plan to make sure that you learn this material. It is critical to being a successful MATLAB programmer.
You have attempted of activities on this page.