Back to tutorial index

The 'dot' operator : Arithmetic expressions involving arrays


Topics in this lab

Introduction

One of the most powerful aspects of Matlab is that many expressions can be vectorized. Whereas in other languages, you might need a loop to carry out simple mathematical operations on each entry of an array, in Matlab, these operations can be carried out in a single line of code. For example, to add the elements of two arrays together using a loop, you might write

for i = 1:10
   z(i) = x(i) + y(i);
end

But in Matlab, we can accomplish the same operation in a single line of code:

z = x + y

The syntax isn't always quite as easy as you see above, but in many cases, vectorization can save you many lines of coding.

clear all
format short

Note on using the 'semicolon' to suppress array output



To suppress the output of any expression, simply terminate the expression with a semicolon ';'. In the following, you'll only see selected output printed to the command line.

u = [1,2,3,4,5];
v = [5,6,7,8,9];
w = u + v
w =

     6     8    10    12    14

Using the semicolon, we can control exactly when we see the output and when we do not need to see it.

Back to the top

Arithmetic operations involving arrays

We can include arrays in arithmetic operations almost as easily as we can compute using scalar variables. For most of the examples in this lab, we will set up a vector containing equally spaced points using the linspace command.

x = linspace(0,1,11)
x =

  Columns 1 through 7

         0    0.1000    0.2000    0.3000    0.4000    0.5000    0.6000

  Columns 8 through 11

    0.7000    0.8000    0.9000    1.0000

To multiply every entry by 2, we can simply write

y = 2*x
y =

  Columns 1 through 7

         0    0.2000    0.4000    0.6000    0.8000    1.0000    1.2000

  Columns 8 through 11

    1.4000    1.6000    1.8000    2.0000

This simple command produced a variable y whose entries are twice that of all the corresponding entries in x. Here are a few more examples.

z = cos(pi*x)
z =

  Columns 1 through 7

    1.0000    0.9511    0.8090    0.5878    0.3090    0.0000   -0.3090

  Columns 8 through 11

   -0.5878   -0.8090   -0.9511   -1.0000

w = log(exp(3*x + 1))
w =

  Columns 1 through 7

    1.0000    1.3000    1.6000    1.9000    2.2000    2.5000    2.8000

  Columns 8 through 11

    3.1000    3.4000    3.7000    4.0000

u = x + y - 4*z
u =

  Columns 1 through 7

   -4.0000   -3.5042   -2.6361   -1.4511   -0.0361    1.5000    3.0361

  Columns 8 through 11

    4.4511    5.6361    6.5042    7.0000

At this point, we can even plot a simple curve.

x = linspace(0,2*pi,200);
y = sin(x);
plot(x,y)

In the lab on plotting you can learn how to add a title, axis labels, adjust the axis limits and the aspect ratio of the plot.

Back to the top

The 'dot' operator : Element-wise operations

You may have noticed that in the above examples, we did not include any expressions involving the multiplication or division of arrays with each other. The reason for this is that whereas addition and subtraction and elementary function evaluation are all well defined mathematical meanings when applied to arrays, the operations like x*x are ambiguous. Do we mean a scalar product? Or a matrix multiply in the linear algebra sense? Or something else?

Often, the correct answer is "something else". Suppose we wanted to construct a vector y who entries contained the square of each entry of x. If we try

>> y = x*x

we get the error

Error using  *
Inner matrix dimensions must agree.

In fact, we can also get errors using the / or the ^ operators, as the following example illustrate.

>> 1/x
Error using  /
Matrix dimensions must agree.

>> y = x^2
Error using  ^
Inputs must be a scalar and a square matrix.
To compute elementwise POWER, use POWER (.^) instead.

The problem is that Matlab is expecting that dimensions of our matrices agree in some linear algebra sense. But what we want is to apply our operation to each element of the array. To use Matlab terminology, we want an element-wise operation. We do this in Matlab by putting a "dot" in front of our multiplication, division or exponentiation operators. The resulting "dot" operators are '.*', ./ or '.^'. For example, either one of the following expressions will give us our desired vector y.

x = 0:4
x =

     0     1     2     3     4

y = x.*x
y =

     0     1     4     9    16

y = x.^2
y =

     0     1     4     9    16

We can now take the element-wise inverse of each entry of x:

y = 1./x
y =

       Inf    1.0000    0.5000    0.3333    0.2500

Using exponentiation with dot operator will also work in this case

y = x.^(-1)
y =

       Inf    1.0000    0.5000    0.3333    0.2500

You notice that the first entry is the special value Inf, which results when we divide by 0.

Back to the top

Rules for using dot operators

Here is a simple set of guidelines for how to use dot operators to carry out element-wise operations

Guidelines for using the dot operators .*, ./ and .^ for element-wise array operations
  1. Multiplication: If both expressions on either side of the mutiplication symbol are arrays, then use the .* operator. If one of the expressions is a scalar, then no dot is needed.
  2. Division: If the numerator is a scalar and the denominator is an array, use the ./ operator. If both the numerator and the denominator are arrays, also use the ./ operator. If the numerator is an array, and the denominator is a scalar, then no dot is needed.
  3. Exponentiation: If either the base or the power (or both) is an array, use the .^ operator. If neither is an array, then no dot is needed.
  4. Addition and subtraction: Dots are never used and are not allowed.
  5. For complicated expressions, apply the above rules recursively,

We can now extend our use of the dot operator to more complicated expressions. In each of the following examples, we wish to evaluate the given expression at an array of values x where x is defined as

x = linspace(0,1,11)
x =

  Columns 1 through 7

         0    0.1000    0.2000    0.3000    0.4000    0.5000    0.6000

  Columns 8 through 11

    0.7000    0.8000    0.9000    1.0000

Example 1
$$y = \cos(\pi x)\sin(\pi x)$$ where the variable $x$ is an array.

y = cos(pi*x).*sin(pi*x)
y =

  Columns 1 through 7

         0    0.2939    0.4755    0.4755    0.2939    0.0000   -0.2939

  Columns 8 through 11

   -0.4755   -0.4755   -0.2939   -0.0000

Example 2
$$y = \frac{\sin(\pi x)}{\cos(\pi x)+2}$$

y = sin(pi*x)./(cos(pi*x)+2)
y =

  Columns 1 through 7

         0    0.1047    0.2092    0.3126    0.4119    0.5000    0.5624

  Columns 8 through 11

    0.5729    0.4935    0.2946    0.0000

Example 3
$$y = 2^{10 x}$$

y = 2.^(10*x)
y =

  Columns 1 through 6

           1           2           4           8          16          32

  Columns 7 through 11

          64         128         256         512        1024

Example 4
$$y = \exp(-10(x-1)^2)^{-1}$$

y = exp(-10*(x-1).^2).^(-1)
y =

   1.0e+04 *

  Columns 1 through 7

    2.2026    0.3294    0.0602    0.0134    0.0037    0.0012    0.0005

  Columns 8 through 11

    0.0002    0.0001    0.0001    0.0001

or

y = 1./exp(-10*(x-1).^2)
y =

   1.0e+04 *

  Columns 1 through 7

    2.2026    0.3294    0.0602    0.0134    0.0037    0.0012    0.0005

  Columns 8 through 11

    0.0002    0.0001    0.0001    0.0001

Back to the top

Lab exercises

Evaluate each of the following expressions using x defined as
x = linspace(-1,1,21);

Use the dot operators .*, ./ and .^ only where needed.
  1. $y = 4x-12$
  2. $y = \tanh(x/10)$
  3. $y = -2(x + 3)^2 + 5$
  4. $y = \frac{3x^3 - 1}{x^2 + 3}$
  5. $y = xe^{-x}$
  6. $y = \frac{1}{x^2 + 1}$
  7. $y = e^{-10(x-2)^2}$
  8. $y = (x + 2)^{\sin(2\pi x)}$
  9. $y = 5x^{-2} - 1 + x + \frac{x^2}{2}$
  10. $y = \cosh^2(\cos(\pi x)) - \sinh^2(\cos(\pi x))$
  11. $y = \frac{\sin(2\pi x)}{x + 2} + 2 \pi \log(x + 2) \cos(2 \pi x)$
Evaluate the following expressions in two different ways. First, use the Matlab functions mean, median and std. Then, compute the same value without using these functions, .i.e. evalute the mathematical expresssions directly, using elementary Matlab functions and operations.
  1. $\displaystyle{\frac{1}{n}\sum_{k=1}^n {x_k}}$
  2. $\sigma = \displaystyle{\sqrt{\frac{1}{n-1}\sum_{k=1}^n (x_k - \mu)^2}}$, where $\displaystyle{\mu = \frac{1}{n}\sum_{k=1}^n x_k}$
  3. Find the value $\tilde{x}$ in $x$ such that half of the values $x_k$ are less than $\tilde{x}$ and half are greater than $\tilde{x}$.
Approximate the circumference of a circle of radius 0.5 by computing the perimeter of an N sided polygon whose vertices are equally spaced points on the circle.

The formula for computing the perimeter of the polygon approximating the circle is $$ C = \sum_{i=1}^{N} \sqrt{(x_{i+1}-x_i)^2 + (y_{i+1}-y_i)^2} $$ To use this formula, you will need to do the following :
  1. Construct two arrays x and y of length N containing the x and y coordinates of the vertices of the polygon.
  2. Create a third array whose entries are the lengths of each edge of the polygon.
  3. Sum up the lengths to get an approximation to the circumference of the circle. For this problem, use the array functions diff and sum.
    Answer the following questions.
    1. As you increase the number of points, what number does your approximation approach?
    2. What is a formula for the exact perimeter of the polygon? Use this to check your approximation.
An ant crawls up and over its ant hill every day. The ant hill is described by the curve $y = \sin(x)$ for $x$ between 0 and $\pi$. How far does the ant travel each day?

  1. Use fprintf and a for loop to print out a table for range of values N values for the number of points to use. For example, use N = [10,20,40,80,160,320].
  2. Compare your answer to the exact solution, given by $$ p = \int_0^\pi \sqrt{1 + \cos^2(x)} \; dx = 2\,\sqrt{2}\,E(0.5) $$
    where $E(m)$ is an complete elliptic integral of the second kind. Use the Matlab function ellipke to evaluate this expression.
    >> [~,E] = ellipke(0.5);
    >> fprintf('Length of the ant path : %11.8f\n',2*sqrt(2)*E);
    
    Length of the ant path :  3.82019779
    

For this problem, use the functions diff and sum.

Here is a sample table showing the distance over the hill, and the error in the approximation.

   N                     Hill        Error
-------------------------------------------
   10       3.8152827260883835   4.9151e-03
   20       3.8189667565027188   1.2310e-03
   40       3.8198898891472157   3.0790e-04
   80       3.8201208051967388   7.6984e-05
  160       3.8201785425161430   1.9247e-05
  320       3.8201929773652057   4.8117e-06
  640       3.8201965861099207   1.2029e-06

Compare your answers with the solutions.

Back to the top

Get the code

Do you want to try the above code fragments on your own? Download the Matlab script that produces this page here. (lab_31.m)

Powered by MathJax

Published with MATLAB® 8.5