%% The 'dot' operator : Arithmetic expressions involving arrays % %% 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 %% % % Using the semicolon, we can control exactly when we see the output and % when we do not need to see it. % %% 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) %% % % To multiply every entry by 2, we can simply write % y = 2*x %% % % 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) %% w = log(exp(3*x + 1)) %% u = x + y - 4*z %% % % 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. % %% 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 %% y = x.*x %% y = x.^2 %% % % We can now take the element-wise inverse of each entry of x: % y = 1./x %% % % Using exponentiation with dot operator will also work in this case % y = x.^(-1) %% % % You notice that the first entry is the special value Inf, which results when we divide by 0. %

% %% 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. %
3. 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. %
4. 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. %
5. Addition and subtraction: Dots are never used and are not allowed. %
6. 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) %% % % Example 1
% % $$y = \cos(\pi x)\sin(\pi x)$$ % where the variable $x$ is an array. % % y = cos(pi*x).*sin(pi*x) %% % % Example 2
% % $$y = \frac{\sin(\pi x)}{\cos(\pi x)+2}$$ % % % y = sin(pi*x)./(cos(pi*x)+2) %% % % Example 3
% % $$y = 2^{10 x}$$ % % % y = 2.^(10*x) %% % % Example 4
% % $$y = \exp(-10(x-1)^2)^{-1}$$ % % % y = exp(-10*(x-1).^2).^(-1) %% % % or % y = 1./exp(-10*(x-1).^2) %% 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. %
3. $y = \tanh(x/10)$
4. %
5. $y = -2(x + 3)^2 + 5$
6. %
7. $y = \frac{3x^3 - 1}{x^2 + 3}$
8. %
9. $y = xe^{-x}$
10. %
11. $y = \frac{1}{x^2 + 1}$
12. %
13. $y = e^{-10(x-2)^2}$
14. %
15. $y = (x + 2)^{\sin(2\pi x)}$
16. %
17. $y = 5x^{-2} - 1 + x + \frac{x^2}{2}$
18. %
19. $y = \cosh^2(\cos(\pi x)) - \sinh^2(\cos(\pi x))$
20. %
21. $y = \frac{\sin(2\pi x)}{x + 2} + 2 \pi \log(x + 2) \cos(2 \pi x)$
22. %
%
%
% 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. %
3. % $\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}$
4. %
5. 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}$.
6. %
%
%
% 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. %
3. Create a third array whose entries are the lengths of % each edge of the polygon.
4. %
5. 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. %
3. What is a formula for the exact perimeter of the polygon? Use % this to check your approximation.
4. % %
%
% 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. %
3. 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
% 
4. %
%

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
% 
%
%
% %% % %