Skip to main content

Section 10.2 Multiplication, Division, and Exponentiation with Arrays

If we want to perform element-by-element multiplication (or division, or exponentiation) on arrays it is almost identical to addition or subtraction, with just one tiny difference. What I mean by element-by-element multiplication would look like this in the general case:
\begin{equation*} [A]*[B]= \begin{bmatrix} a_{11}*b_{11} & a_{12}*b_{12} \\ a_{21}*b_{21} & a_{22}*b_{22} \end{bmatrix} \end{equation*}
So if we multiply a 2x2 matrix \([A]\) with a 2x2 matrix \([B]\text{,}\) the output is the multiplication of the corresponding elements. Hopefully, you still have the 4 variables still stored in your Workspace.
Stop and Think
Before continuing, THINK about multiplying mat1*mat2 and storing in a new matrix called huh. What should the value of huh(1,1) be? Do not skip your brain workout! It only takes one second and will make the following example much more compelling.
Ok, now that you have a prediction for what happens, go ahead and type in huh = mat1 * mat2 into the command window.

Example 10.2.1. Multiplying mat1 and mat2 (Part 1).

Here is an interactive code box that functions identically to the MATLAB command window.

Checkpoint 10.2.2. Values in matrix huh.

So did we break MATLAB? Is MATLAB incapable of doing such a simple mathematical operation? The value of mat1(1,1) is \(4\) and the value of mat2(1,1) is \(-10\) so \(4*-10\) should equal \(-40\) so why is the number \(20\) showing up in huh(1,1)?
Don’t worry, MATLAB is NOT broken. It is simply doing a different type of math than what you are expecting. I’ll explain what is happening in a bit, but for now, try the exact same operation, but this time, add a . before the * and let’s store the result in a new matrix called oh_okay. Type the following into the command window:
oh_okay = mat1 .* mat2

Example 10.2.3. Multiplying mat1 and mat2 (Part 2).

Here is an interactive code box that functions identically to the MATLAB command window.

Checkpoint 10.2.4. Values in matrix oh_okay.

Now THAT looks like what we are expecting! So what is going on?
Remember that quick note at the beginning of the chapter? The reason you need to add the . for multiplication is to signify element-by-element operations. The * is reserved for linear algebra multiplication (as are the / and ^ symbols) so we need to specify the . to let MATLAB know we want to perform element-by-element operations.
That means that unless you are specifically doing linear algebra, you will want to put a . before you perform multiplication, division, or exponentiation with arrays. Do not indiscriminately add dots to your equations! Figure 10.2.5 below shows the only times that you need dots.
Figure 10.2.5. When to use the . operator
You have attempted of activities on this page.