%% Powers and Exponentials
% This topic shows how to compute matrix powers and exponentials using a variety of methods.
%
%% Positive Integer Powers
% If A is a square matrix and p is a positive integer, then A^p effectively multiplies A by itself p-1 times. For example:

A = [1 1 1
     1 2 3
     1 3 6];
A^2

%
%% Inverse and Fractional Powers
% If A is square and nonsingular, then A^(-p) effectively multiplies inv(A) by itself p-1 times.

A^(-3)

% MATLAB® calculates inv(A) and A^(-1) with the same algorithm, so the results are exactly the same. Both inv(A) and A^(-1) produce warnings if the matrix is close to being singular.

isequal(inv(A),A^(-1))

% Fractional powers, such as A^(2/3), are also permitted. The results using fractional powers depend on the distribution of the eigenvalues of the matrix.

A^(2/3)

%
%% Element-by-Element Powers
% The .^ operator calculates element-by-element powers. For example, to square each element in a matrix you can use A.^2.

A.^2

%
%% Square Roots
% The sqrt function is a convenient way to calculate the square root of each element in a matrix. An alternate way to do this is A.^(1/2).

sqrt(A)

% For other roots, you can use nthroot. For example, calculate A.^(1/3).

nthroot(A,3)

% These element-wise roots differ from the matrix square root, which calculates a second matrix B such that A=\textrm{BB}. The function sqrtm(A) computes A^(1/2) by a more accurate algorithm. The m in sqrtm distinguishes this function from sqrt(A), which, like A.^(1/2), does its job element-by-element.

B = sqrtm(A)
B^2

%
%% Scalar Bases
% In addition to raising a matrix to a power, you also can raise a scalar to the power of a matrix.

2^A

% When you raise a scalar to the power of a matrix, MATLAB uses the eigenvalues and eigenvectors of the matrix to calculate the matrix power. If [V,D] = eig(A), then 2^A ={V\;2}^D {\;V}^{-1}.

[V,D] = eig(A);
V*2^D*V^(-1)

%
%% Matrix Exponentials
% The matrix exponential is a special case of raising a scalar to a matrix power. The base for a matrix exponential is Euler's number e = exp(1).

e = exp(1);
e^A

% The expm function is a more convenient way to calculate matrix exponentials.

expm(A)

% The matrix exponential can be calculated in a number of ways. See Matrix Exponentials for more information.
%
%% Dealing with Small Numbers
% The MATLAB functions log1p and expm1 calculate \log \left(1+x\right) and e^x -1 accurately for very small values of x. For example, if you try to add a number smaller than machine precision to 1, then the result gets rounded to 1.

log(1+eps/2)

% However, log1p is able to return a more accurate answer.

log1p(eps/2)

% Likewise for e^x -1, if x is very small then it is rounded to zero.

exp(eps/2)-1

% Again, expm1 is able to return a more accurate answer.

expm1(eps/2)

%
% Copyright 2019 The MathWorks, Inc.
%