UP
PDF letter size
PDF legal size

How to solve basic engineering and mathematics problems using Mathematica, Matlab and Maple

July 1, 2016 compiled on — Friday July 01, 2016 at 09:48 AM

This is a collection of how to examples showing the use of Mathematica and Matlab to solve basic engineering and mathematics problems. Few examples are also in Maple, Ada, and Fortran.

This was started as a cheat sheet few years ago, and I continue to update it all the time.

Few of the Matlab examples require the use of toolboxs such as signal processing toolbox and the control systems toolbox (these come free as part of the student version). Most examples require only the basic system installation.

1  Control systems, Linear systems, transfer functions, state space related problems
2  Linear algebra, Linear solvers, common operations on vectors and matrices
3   signal processing, Image processing, graphics, random numbers
4  Differential, PDE solving, integration, numerical and analytical solving of equations
5  plotting how to, ellipse, 3D

1  Control systems, Linear systems, transfer functions, state space related problems

 1.1  Creating tf and state space and different Conversion of forms
 1.2  Obtain the step response of an LTI from its transfer function
 1.3  plot the impulse and step responses of a system from its transfer function
 1.4  Obtain the response of a transfer function for an arbitrary input
 1.5  Obtain the poles and zeros of a transfer function
 1.6  Generate Bode plot of a transfer function
 1.7  How to check that state space system x′ = Ax + Bu  is controllable?
 1.8  Obtain partial-fraction expansion
 1.9  Obtain Laplace transform for a piecewise functions
 1.10  Obtain Inverse Laplace transform of a transfer function
 1.11  Display the response to a unit step of an under, critically, and over damped system
 1.12  View steady state error of 2nd order LTI system with changing undamped natural frequency
 1.13  Show the use of the inverse Z transform
 1.14  Find the Z transform of sequence x(n)
 1.15  Sample a continuous time system
 1.16  Find closed loop transfer function from the open loop transfer function for a unity feedback
 1.17  Compute the Jordan canonical/normal form of a matrix A
 1.18  Solve the continuous-time algebraic Riccati equation
 1.19  Solve the discrete-time algebraic Riccati equation
 1.20  Display impulse response of H(z) and the impulse response of its continuous time approximation H(s)
 1.21  Find the system type given an open loop transfer function
 1.22  Find the eigenvalues and eigenvectors of a matrix
 1.23  Find the characteristic polynomial of a matrix
 1.24  Verify the Cayley-Hamilton theorem that every matrix is zero of its characteristic polynomial
 1.25  How to check for stability of system represented as a transfer function and state space
 1.26  Check continuous system stability in the Lyapunov sense
 1.27  Given a closed loop block diagram, generate the closed loop Z transform and check its stability
 1.28  Determine the state response of a system to only initial conditions in state space
 1.29  Determine the response of a system to only initial conditions in state space
 1.30  Determine the response of a system to step input with nonzero initial conditions
 1.31  Draw the root locus from the open loop transfer function
 1.32  Find eAt  where A  is a matrix
 1.33  Draw root locus for a discrete system
 1.34  Plot the response of the inverted pendulum problem using state space
 1.35  How to build and connect a closed loop control systems and show the response?
 1.36  Compare the effect on the step response of a standard second order system as ζ  changes
 1.37  Plot the dynamic response factor Rd  of a system as a function of     ω-
r = ωn   for different damping ratios
 1.38  How to find closed loop step response to a plant with a PID controller?
 1.39  How to make Nyquist plot?

1.1  Creating tf and state space and different Conversion of forms

1.1.1  Create continuous time transfer function given the poles, zeros and gain

Problem: Find the transfer function H (s)  given zeros s = − 1,s = − 2  , poles s = 0, s = − 4, s = − 6  and gain 5.



Mathematica

 
Out[30]= TransferFunctionModel[{ 
     {{5*(1 + s)*(2 + s)}}, 
     s*(4 + s)*(6 + s)}, s]



 


Matlab

 
num/den = 
    5 s^2 + 15 s + 10 
   ------------------- 
   s^3 + 10 s^2 + 24 s



 


Maple

     [ 5s2+15s+10]
tf =  s3+10s2+24s



    2
5 ∗ s + 15 ∗ s + 10



s ∗ (s2 + 10 ∗ s + 24)



 

1.1.2  Convert transfer function to state space representation

problem 1

Problem: Find the state space representation for the continuous time system defined by the transfer function

H (s) = -----5s-----
        s2 + 4s + 25



Mathematica

pict



pict



 


Matlab

 
A = 
    -4   -25 
     1     0 
B = 
     1 
     0 
C = 
     5     0 
D = 
     0



 


Maple

[        ]
   0   1
  − 25 − 4



[0 ]

  1



[  ]
 05



[0]



 

problem 2

Problem: Given the continuous time S transfer function defined by

           1 + s
H (s) = --2-------
        s  + s + 1

convert to state space and back to transfer function.



Mathematica

( 0  1 0)
(− 1− 11)
  1  1 0

--s-+-1---
s2 + s + 1



 


Matlab

 
A = 
    -1    -1 
     1     0 
 
B = 
     1 
     0 
 
C = 
     1     1 
 
D = 
     0



 
sys = 
     s + 1 
  ----------- 
  s^2 + s + 1



 

1.1.3  Create a state space representation from A,B,C,D and find the step response

Problem: Find the state space representation and the step response of the continuous time system defined by the Matrices A,B,C,D as shown

 
A = 
     0     1     0     0 
     0     0     1     0 
     0     0     0     1 
  -100   -80   -32    -8 
 
B = 
     0 
     0 
     5 
    60 
 
C = 
     1     0     0     0 
 
D = 
     0


Mathematica

pict



 


Matlab

pict



 


Maple

pict



 

1.1.4  Convert continuous time to discrete time transfer function, gain and phase margins

Problem: Compute the gain and phase margins of the open-loop discrete linear time system sampled from the continuous time S transfer function defined by

           1 + s
H (s) = --2-------
        s  + s + 1

Use sampling period of 0.1 seconds.



Mathematica

pict



pict



gm  Out [28 ]={{31.4159,19.9833   }} pm   Out [29]= {{1.41451,1.83932   },{0.,Pi }}



pict



 


Matlab

 
   0.09984 z - 0.09033 
  ---------------------- 
  z^2 - 1.895 z + 0.9048 
 
Sample time: 0.1 seconds 
Discrete-time transfer function. 
 
Gm = 
   19.9833 
 
Pm = 
  105.3851 
 
Wcg = 
   31.4159 
 
Wcp = 
    1.4145



pict



 

1.1.5  Convert differential equation to transfer functions and to state space

Problem: Obtain the transfer and state space representation for the differential equation

  2
3d-y-+ 2 dy-+ y (t) = u(t)
 dt2     dt



Mathematica

pict



pict



 


Matlab

 
        1 
  -------------- 
     2 
  3 s  + 2 s + 1



 
A = 
   -0.6667   -0.3333 
    1.0000         0 
B = 
     1 
     0 
C = 
         0    0.3333 
D = 
     0



 


Maple

-----1------
3s2 + 2s + 1



{ [       ] [ ]        }
    0   1  , 0 ,[1∕30],[0]
   −1∕3− 2∕3   1



 

1.1.6  Convert from continuous transfer function to discrete time transfer function

Problem: Convert

H (s) = ------1-------
        s2 + 10s + 10

To Z  domain transfer function using sampling period of 0.01  seconds and using the zero order hold method.



Mathematica

pict



 


Matlab

 
sysz = 
 
  4.837e-05 z + 4.678e-05 
  ----------------------- 
  z^2 - 1.903 z + 0.9048 
 
Sample time: 0.01 seconds 
Discrete-time transfer function.



 

1.1.7  Convert a Laplace transfer function to an ordinary differential equation

Problem: Give a continuous time transfer function, show how to convert it to an ordinary differential equation. This method works for non-delay systems. The transfer function must be ratio of polynomials. For additional methods see this question at stackexchange



Mathematica

 
25 + 4 y'[t]+y''[t]==5 u'[t]



 

1.2  Obtain the step response of an LTI from its transfer function

Problem: Find the unit step response for the continuous time system defined by the transfer function

        -----25-----
H (s) = s2 + 4s + 25



Mathematica

pict



 


Matlab

pict



 


Maple

pict



 

1.3  plot the impulse and step responses of a system from its transfer function

Problem: Find the impulse and step responses for the continuous time system defined by the transfer function

        ------1------
H (s) = s2 + 0.2s + 1

and display these on the same plot up to some t  value.

Side note: It was easier to see the analytical form of the responses in Mathematica and Maple so it is given below the plot.



Mathematica

 
{1 - E^(-t/10) Cos[(3 Sqrt[11] t)/10] 
 - ( 
E^(-t/10) Sin[(3 Sqrt[11]t)/10])/ 
                       (3 Sqrt[11])}



 
{(10 E^(-t/10) HeavisideTheta[t] 
  Sin[(3 Sqrt[11] t)/10])/(3 Sqrt[11])}



pict



 


Matlab

pict



 


Maple

Using Maple DynamicSystems

pict



Using Laplace transform method:

pict



 

1.4  Obtain the response of a transfer function for an arbitrary input

Problem: Find the response for the continuous time system defined by the transfer function

H (s) = ------1------
        s2 + 0.2s + 1

when the input is given by

u (t) = sin(t)

and display the response and input on the same plot.

Side note: It was easier to see the analytical form of the responses in Mathematica and Maple so it is given below the plot.



Mathematica

pict



 


Matlab

pict



 


Maple

pict



Using DynamicSystem package

pict



 

1.5  Obtain the poles and zeros of a transfer function

Problem: Find the zeros, poles, and gain for the continuous time system defined by the transfer function

        -----25-----
H (s) = s2 + 4s + 25



Mathematica

 
             {{{}}}



 
{{{-2.-4.58258 I,-2.+4.58258 I}}}



 


Matlab

 
 
z = 
   Empty matrix: 0-by-1 
 
p = 
  -2.0000 + 4.5826i 
  -2.0000 - 4.5826i



 


Maple

 
zeros:= [] 
poles:= [-2.000000000-4.582575695*I, 
         -2.+4.582575695*I]



 

1.6  Generate Bode plot of a transfer function

Problem: Generate a Bode plot for the continuous time system defined by the transfer function

        -----5s-----
H (s) = s2 + 4s + 25



Mathematica

pict



 


Matlab

pict



 


Maple

or can plot the the two bode figures on top of each others as follows

pict



 

1.7  How to check that state space system x′ = Ax +  Bu  is controllable?

A system described by

pict

Is controllable if for any initial state x
  0   and any final state x
 f  there exist an input u  which moves the system from x0   to xf  in finite time. Only the matrix A  and B  are needed to decide on controllability. If the rank of

        2        n− 1
[B  AB  A B  ... A   B ]

is n  which is the number of states, then the system is controllable. Given the matrix

     (               )
        0  1   0   0
A =  ||  0  0  − 1  0 ||
     (  0  0   0   1 )
        0  0   5   0

And

    (      )
        0
    |   1  |
B = |(      |)
        0
       − 2



Mathematica

(               )
   0  1  0   2
|  1  0  2   0  |
|(  0 − 2 0  − 10 |)

  − 2 0 − 10 0



True



4



 


Matlab

 
m = 
     0     1     0     2 
     1     0     2     0 
     0    -2     0   -10 
    -2     0   -10     0



4



 


Maple

⌊              ⌋
  0  1  0   2
|              |
|| 1  0  2   0  ||
| 0 − 2 0  − 10|
⌈              ⌉
 − 2 0 − 10 0



true



true



4



 

1.8  Obtain partial-fraction expansion

Problem: Given the continuous time S transfer function defined by

         s4 + 8s3 + 16s2 + 9s + 9
H (s) =  ------------------------
           s3 + 6s2 + 11s + 6

obtain the partial-fractions decomposition.

Comment: Mathematica result is easier to see visually since the partial-fraction decomposition returned in a symbolic form.



Mathematica

 
2 + s +3/(1+s) -4/(2+s) -6/(3+s)



 


Matlab

 
r = 
   -6.0000 
   -4.0000 
    3.0000 
 
p = 
   -3.0000 
   -2.0000 
   -1.0000 
 
k = 
     1     2



 


Maple

s+ 2− -7--− --9--+ --9--
      s+ 2  2s+ 6  2s+2

[s,2,--7--,− ---9---,--9---]
     s + 2   2s + 6  2s + 2



 

1.9  Obtain Laplace transform for a piecewise functions

Problem: Obtain the Laplace transform for the function defined in the following figure.

pict

Function f(t) to obtain its Laplace transform

Comment: Mathematica solution was easier than Matlab’s. In Matlab the definition of the Laplace transform is applied to each piece separately and the result added. Not finding the piecewise maple function to access from inside MATLAB did not help.



Mathematica

 
Out[]= (1 - E^((-s)*T))/s^2



 


Matlab

 
  1 - exp(-T s) 
  ------------- 
        2 
       s



 


Maple

With Maple, had to use Heaviside else Laplace will not obtain the transform of a piecewise function.

1-−-e−sT-
   s2



 

1.10  Obtain Inverse Laplace transform of a transfer function

Problem: Obtain the inverse Laplace transform for the function

        --s4 +-5s3-+-6s2-+-9s-+-30
H (s) = s4 + 6s3 + 21s2 + 46s + 30

Mathematica

      (            )         (                             )     − 3t      − t
δ(t) +  -1--+  -i--  e(− 1− 3i)t (73 + 326i)e6it + (− 326 − 73i) − 3e--- + 23e---
        234    234                                              26       18

Matlab

 
    4      3      2 
   s  + 5 s  + 6 s  + 9 s + 30 
  ----------------------------- 
   4      3       2 
  s  + 6 s  + 21 s  + 46 s + 30
 
                                                    /            399 sin(3 t) \ 
                                        253 exp(-t) | cos(3 t) + ------------ | 
  23 exp(-t)   3 exp(-3 t)                          \                253      / 
  ---------- - ----------- + dirac(t) - --------------------------------------- 
      18           26                                     117

Maple

            3e−3t   (− 506-cos(3t)-−-798-sin-(3t) +-299-)e−t
Dirac (t) −  26  +                   234

1.11  Display the response to a unit step of an under, critically, and over damped system

Problem: Obtain unit step response of the second order system given by the transfer function

         ------ω2n-------
H  (s ) = s2 + 2ξ ωns + ω2
                       n

in order to illustrate the response when the system is over, under, and critically damped. use ωn =  1  and change ξ  over a range of values that extends from under damped to over damped.

Mathematica

pict

Matlab

pict

Maple

Instead of using Simulate as above, another option is to use ResponsePlot which gives same plot as above.

pict

1.12  View steady state error of 2nd order LTI system with changing undamped natural frequency

Problem: Given the transfer function

               ω2
H  (s ) = -2------n-----2-
         s + 2ξ ωns + ωn

Display the output and input on the same plot showing how the steady state error changes as the un damped natural frequency ωn  changes. Do this for ramp and step input.

The steady state error is the difference between the input and output for large time. In other words, it the difference between the input and output at the time when the response settles down and stops changing.

Displaying the curve of the output and input on the same plot allows one to visually see steady state error.

Use maximum time of 10  seconds and ξ = 0.707  and change ωn  from 0.2  to 1.2  .

Do this for ramp input and for unit step input. It can be seen that with ramp input, the steady state do not become zero even at steady state. While with step input, the steady state error can become zero.

1.12.1  Mathematica

ramp input

pict

step input

pict

1.13  Show the use of the inverse Z transform

These examples show how to use the inverse a Z transform.

1.13.1  example 1

Problem: Given

          z
F (z) = ------
        z − 1

find          −1
x [n ] = F   (z)  which is the inverse Ztransform.



Mathematica

pict



 


Matlab

pict



 

1.13.2  example 2

Problem: Given

           5z
F (z) =  ------2-
         (z − 1)

find x [n ] = F −1 (z)

In Mathematica analytical expression of the inverse Z transform can be generated as well as shown below



Mathematica

Inverse Z is 5 n

pict



 


Matlab

pict



 

1.14  Find the Z transform of sequence x(n)

1.14.1  example 1

Find the Z transform for the unit step discrete function

Given the unit step function x[n] = u[n]  defined as x = {1, 1,1,⋅⋅⋅}  for n ≥ 0  , find its Z transform.



Mathematica

 
 
Out[] = z/(-1+z)



 


Matlab

 
 
    1 
  ----- + 1/2 
  z - 1



 

1.14.2  example 2

Find the Z transform for        (1)n             n−3
x[n] =  3   u (n ) + (0.9)   u(n)



Mathematica

 
z (3/(-1+3 z)+10000/(729 (-9+10 z)))



 


Matlab

 
       100           1 
  ------------- + ------- + 1729/1458 
  81 (z - 9/10)   3 z - 1



 

1.15  Sample a continuous time system

Given the following system, sample the input and find and plot the plant output

pict

Use sampling frequency f = 1  Hz and show the result for up to 14  seconds. Use as input the signal u(t) = exp (− 0.3t)sin(2π (f ∕3)t)  .

Plot the input and output on separate plots, and also plot them on the same plot.

Mathematica

pict

pict

pict

Matlab

 
plantD = 
 
     0.6976 z - 0.6976 
  ------------------------ 
  z^2 - 0.5032 z + 0.04979 
 
Sample time: 1 seconds 
Discrete-time transfer function.

pict

1.16  Find closed loop transfer function from the open loop transfer function for a unity feedback

Problem: Given

L(s) = ------s-------
       (s + 4)(s + 5)

as the open loop transfer function, how to find G (s)  , the closed loop transfer function for a unity feedback?

pict



Mathematica

pict



pict



The system wrapper can be removed in order to obtain the rational polynomial expression as follows

------s-------
s2 + 10s + 20



 


Matlab

 
Transfer function: 
       s 
--------------- 
s^2 + 10 s + 20



 

1.17  Compute the Jordan canonical/normal form of a matrix A



Mathematica

(                )
  3− 1 1 1  0  0
| 1 1 − 1− 1 0 0 |
|| 0 0 2  0  1  1 ||
||                ||
| 0 0 0  2 − 1− 1|
( 0 0 0  0  1  1 )
  0 0 0  0  1  1



(        )
  000000
| 021000 |
|| 002000 ||
||        ||
| 000210 |
( 000021 )
  000002



 


Matlab

 
ans = 
 0     0     0     0     0     0 
 0     2     1     0     0     0 
 0     0     2     1     0     0 
 0     0     0     2     0     0 
 0     0     0     0     2     1 
 0     0     0     0     0     2



 

1.18  Solve the continuous-time algebraic Riccati equation

Problem: Solve for X  in the Riccati equation

  ′                −1  ′      ′
A X  + XA  −  XBR    B  X + C  C =  0

given

pict


Mathematica

(0.5895171.82157  )

  1.82157 8.81884



 


Matlab

 
x = 
    0.5895    1.8216 
    1.8216    8.8188



 

1.19  Solve the discrete-time algebraic Riccati equation

Problem: Given a continuous-time system represented by a transfer function

----1-----
s(s + 0.5)

convert this representation to state space and sample the system at sampling period of 1  second, and then solve the discrete-time Riccati equation.

The Riccati equation is given by

  ′                −1  ′      ′
A X  + XA  −  XBR    B  X + C  C =  0

Let R  = [3]  .



Mathematica

pict



pict



( 0.671414  − 0.977632 )

  − 0.977632 2.88699



 


Matlab

 
dsys = 
    0.4261 z + 0.3608 
  ---------------------- 
  z^2 - 1.607 z + 0.6065 
 
Sample time: 1 seconds 
Discrete-time transfer function.



 
A = 
    1.6065   -0.6065 
    1.0000         0 
B = 
     1 
     0 
C = 
    0.4261    0.3608 
D = 
     0 
 
    2.8870   -0.9776 
   -0.9776    0.6714



 
ans = 
 
    2.8870   -0.9776 
   -0.9776    0.6714



 

1.20  Display impulse response of H(z) and the impulse response of its continuous time approximation H(s)

Plot the impulse response of H (z) = z∕(z2 − 1.4z + 0.5)  and using sampling period of T =  0.5  find continuous time approximation using zero order hold and show the impulse response of the system and compare both responses.

Mathematica

pict

Find its impulse response

 
{0.,1.,1.4,1.46,1.344,1.1516,0.94024,0.740536, 
0.56663,0.423015,0.308905,0.22096,0.154891, 
0.106368,0.0714694,0.0468732,0.0298878, 
0.0184063,0.0108249,0.00595175,0.00291999}

approximate to continuous time, use ZeroOrderHold

pict

Find the impulse response of the continuous time system

          −0.693147t
− 1.25559e        (− 13.3012 θ(t)sin (0.283794t ) − 1.θ(t)cos(0.283794t))

pict

Plot the impulse response of the discrete system

pict

Plot the impulse response of the continuous system

pict

Plot both responses on the same plot

pict

Do the same plot above, using stair case approximation for the discrete plot

pict

Matlab

pict

1.21  Find the system type given an open loop transfer function

Problem: Find the system type for the following transfer functions

  1. s+1-
s2−s
  2.  s+1
s3−s2
  3. s+s51

To find the system type, the transfer function is put in the form   ∑
skM-∑i(s(−s−si)sj)
    j   , then the system type is the exponent M  . Hence it can be seen that the first system above has type one since the denominator can be written as  1
s  (s − 1)  and the second system has type 2 since the denominator can be written as  2
s (s − 1)  and the third system has type 5. The following computation determines the type



Mathematica

Out[171]= 1



Out[173]= 2



Out[175]= 5



 


Matlab

 
ans = 
     1



 
ans = 
     2



 
ans = 
     5



 

1.22  Find the eigenvalues and eigenvectors of a matrix

Problem, given the matrix

(          )
   1  2  3
(  4  5  6 )
   7  8  9

Find its eigenvalues and eigenvectors.



Mathematica

(    )
  123
( 456)
  789



{   (        )    (        )   }
  3-     √ ---  3-     √ ---
  2  5 +   33  ,2  5 −   33  ,0

{16.1168, − 1.11684, 0.}



(       √ -- 4(6+√33)  )
| − −-15−√-33 ----√--- 1|
|    33+7√-33 4(33−+67+√3333)  |
|( − -15−-3√3-------√---1|)
    −33+7 33 −33+7 33
      1        − 2    1

(                      )
  0.283349  0.641675 1.
( − 1.28335 − 0.1416751. )
     1.       − 2.   1.



 


Matlab

Matlab generated eigenvectors are such that the sum of the squares of the eigenvector elements add to one.

 
v = 
   -0.2320   -0.7858    0.4082 
   -0.5253   -0.0868   -0.8165 
   -0.8187    0.6123    0.4082 
 
e = 
   16.1168         0         0 
         0   -1.1168         0 
         0         0   -0.0000



 

1.23  Find the characteristic polynomial of a matrix

(          )
   1  2  3
(  4  5  6 )
   7  8  0



Mathematica

− x3 + 6x2 + 72x + 27



 


Matlab

Note: Matlab generated characteristic polynomial coefficients are negative to what Mathematica generated.

 
p = 
 1.0000 -6.0000 -72.0000 -27.0000 
ans = 
 x^3 - 6 x^2 - 72 x - 27



 

1.24  Verify the Cayley-Hamilton theorem that every matrix is zero of its characteristic polynomial

Problem, given the matrix

( 1  2 )

  3  2

Verify that matrix is a zero of its characteristic polynomial. The Characteristic polynomial of the matrix is found, then evaluated for the matrix. The result should be the zero matrix.



Mathematica

 2
x  − 3x − 4



(   )
 00
 00



Another way is as follows

(   )
 00
 00



 

MATLAB has a build-in function polyvalm() to do this more easily than in Mathematica. Although the method shown in Mathematica can easily be made into a Matlab function



Matlab

 
ans = 
   x^2 - 3 x - 4 
ans = 
     0     0 
     0     0



 

1.25  How to check for stability of system represented as a transfer function and state space

Problem: Given a system Laplace transfer function, check if it is stable, then convert to state space and check stability again. In transfer function representation, the check is that all poles of the transfer function (or the zeros of the denominator) have negative real part. In state space, the check is that the matrix A is negative definite. This is done by checking that all the eigenvalues of the matrix A have negative real part. The poles of the transfer function are the same as the eigenvalues of the A matrix. Use

           5s
sys =  -2----------
       s + 4s + 25

1.25.1  Checking stability using transfer function poles



Mathematica

 
{{{-2-I Sqrt[21],-2+I Sqrt[21]}}}



 
Out[42]= {{{-2,-2}}}



 
Out[44]= {}



 


Matlab

 
>> 
p = 
  -2.0000 + 4.5826i 
  -2.0000 - 4.5826i



 
ans = 
   Empty matrix: 0-by-1



 

1.25.2  Checking stability using state space A matrix



Mathematica

 
Out[49]= {{0,1},{-25,-4}}



 
Out[50]= {-2+I Sqrt[21],-2-I Sqrt[21]}



 
Out[51]= {-2,-2}



 
Out[52]= {}



 


Matlab

 
A = 
   -4.0000   -6.2500 
    4.0000         0



 
e = 
  -2.0000 + 4.5826i 
  -2.0000 - 4.5826i



 
ans = 
   Empty matrix: 0-by-1



 

1.26  Check continuous system stability in the Lyapunov sense

Problem: Check the stability (in Lyapunov sense) for the state coefficient matrix

     ⌊             ⌋
       0    1    0
A  = ⌈ 0    0    1 ⌉

      − 1  − 2  − 3

The Lyapunov equation is solved using lyap() function in MATLAB and LyapunovSolve[] function in Mathematica, and then the solution is checked to be positive definite (i.e. all its eigenvalues are positive).

We must transpose the matrix A  when calling these functions, since the Lyapunov equation is defined as   T
A  P +  PA  = − Q  and this is not how the software above defines them. By simply transposing the A  matrix when calling them, then the result will be correct.



Mathematica

(          )
   0  1  0
(  0  0  1 )
  − 1− 2− 3



(          )
  2.32.10.5
( 2.14.61.3)
  0.51.30.6



{6.18272,1.1149, 0.202375 }



 


Matlab

 
p = 
  2.3   2.1  0.5 
  2.1   4.6  1.3 
  0.5   1.3  0.6



 
e = 
     0.20238 
       1.1149 
       6.1827



 


Maple

⌊ 6.18272045921436+ 0.0i⌋
|                     |
|⌈ 1.11490451203192+ 0.0i|⌉
 0.202375028753723+ 0.0i



 

1.27  Given a closed loop block diagram, generate the closed loop Z transform and check its stability

Problem: Given the following block diagram, with sampling time T =  0.1 sec  , generate the closed loop transfer function, and that poles of the closed loop transfer function are inside the unit circle

pict

System block diagram.

Mathematica

pict

pict

pict

pict

Now generate unit step response

pict

pict

{0.543991 −  0.325556i, 0.543991 + 0.325556i}

(                      )
  {0.633966, 0.633966}

Poles are inside the unit circle, hence stable.

Matlab

 
loop = 
 
   z^2 - 1.801 z + 0.8013 
  ------------------------ 
  2 z^2 - 2.176 z + 0.8038 
 
Sample time: 1 seconds 
Discrete-time transfer function.

pict

 
ans = 
    0.6340 
    0.6340

1.28  Determine the state response of a system to only initial conditions in state space

Problem: Given a system with 2 states, represented in state space, how to determine the state change due some existing initial conditions, when there is no input forces?



Mathematica

pict



pict



 


Matlab

pict



 

1.29  Determine the response of a system to only initial conditions in state space

Problem: Given a system represented by state space, how to determine the response y(t)  due some existing initial conditions in the states. There is no input forces.



Mathematica

pict



pict



 


Matlab

pict



 

1.30  Determine the response of a system to step input with nonzero initial conditions

Problem: Given a system represented by state space, how to determine the response with nonzero initial conditions in the states and when the input is a step input?



Mathematica

pict



pict



 


Matlab

pict



 

1.31  Draw the root locus from the open loop transfer function

Problem: Given L (s)  , the open loop transfer function, draw the root locus. Let

        ---------s2 +-2s-+-4---------
L (s) = s(s + 4 )(s + 6)(s2 + 1.4s + 1)

Root locus is the locus of the closed loop dominant pole as the gain k  is varied from zero to infinity.



Mathematica

pict



 


Matlab

pict



 

1.32  Find  At
e  where A  is a matrix

Mathematica

(                            )
   − e− 2t + 2e−t − e−2t + e−t
   2e−2t − 2e−t  2e− 2t − e−t

Now verify the result by solving for  At
e  using the method would one would do by hand, if a computer was not around. There are a number of methods to do this by hand. The eigenvalue method, based on the Cayley Hamilton theorem will be used here. Find the eigenvalues of |A − λI |

(              )
  − λ     1
  − 2  − λ − 3

 2
λ +  3λ + 2

 
    Out[15]= {{lambda->-2},{lambda->-1}}
 
      Out[16]= -2 
      Out[17]= -1
{b0 →  e− 2t(2et − 1) ,b1 →  e−2t(et − 1)}

e−2t(2et − 1)

     (     )
e− 2t et − 1

(    −2t         t     −2t       t   )
    e  −(2−t 1 + 2e )t   e −2(t− 1 + e )t
   − 2e   (− 1 + e ) − e   (− 2 + e )

The answer is the same given by Mathematica’s command MatrixExp[]

Matlab

 
ans = 
 
[2/exp(t)-1/exp(2*t),1/exp(t)-1/exp(2*t)] 
[2/exp(2*t)-2/exp(t),2/exp(2*t)-1/exp(t)]
 
+-                                        -+ 
| 2 exp(-t)-  exp(-2 t),exp(-t)-exp(-2 t)  | 
|                                          | 
| 2 exp(-2 t)-2 exp(-t),2 exp(-2 t)-exp(-t)| 
+-                                        -+

1.33  Draw root locus for a discrete system

Problem: Given the open loop for a continuous time system as

sys = --5s-+-1---
      s2 + 2s + 3

convert to discrete time using a sampling rate and display the root locus for the discrete system.



Mathematica

pict



pict



 


Matlab

pict



 

1.34  Plot the response of the inverted pendulum problem using state space

Problem: Given the inverted pendulum shown below, use state space using one input (the force on the cart) and 2 outputs (the cart horizontal displacement, and the pendulum angle. Plot each output separately for the same input.

pict

Mathematica

(                   )
   0  1     0     0
|  0  0    − gmM--  0 |
|(  0  0     0     1 |)
          g(m+M-)-
   0  0    LM     0

(    0   )
|    1-  |
|    M   |
(    0   )
   − L1M-

(            )
  1  0  0  0
  0  0  1  0

pict

It is now possible to obtain the response of the system as analytical expression or an interpolatingFunction.

It is much more efficient to obtain the response as interpolatingFunction. This requires that the time domain be given.

Here is example of obtaining the analytical expression of the response

e−6.41561t(0.0238095e6.41561tt2θ(t) + 0.000115693e3.2078tθ(t) − 0.000231385e6.41561tθ(t) + 0.000115693e9.62341tθ(t))
,e−6.41561t(− 0.00242954e3.2078tθ(t) + 0.00485909e6.41561tθ(t) − 0.00242954e9.62341tθ(t))

pict

pict

Matlab

pict

pict

1.35  How to build and connect a closed loop control systems and show the response?

1.35.1  example 1, single input, single output closed loop

Given the following simple closed loop system, show the step response. Let mass M  = 1kg  , damping coefficient c = 1newton -seconds per meter  and let the stiffness coefficient be k =  20newton  per meter  .

pict

Using propertional controller J (s) = kp  where kp = 400  . First connect the system and then show y(t)  for 5 seconds when the reference yr(t)  is a unit step function.

Mathematica

pict

Matlab

Another way to do the above is

pict

1.36  Compare the effect on the step response of a standard second order system as ζ  changes

Problem: Given a standard second order system defined by the transfer function

               ω2
G (s) = --2-----n------2
        s  + 2ζωns +  ωn

Change ζ  and plot the step response for each to see the effect of changing ζ  (the damping coefficient).

It is easy to solve this using the step command in Matlab, and similarly in Mathematica and Maple. But here it is solved directly from the differential equation.

The transfer function is written as

                 2
Y-(s) =  ------ω-n-------
U (s)    s2 + 2 ζωns + ω2n

Where Y (s)  and U (s)  are the Laplace transforms of the output and input respectively.

Hence the differential equation, assuming zero initial conditions becomes

y′′(t) + 2ζωn y ′(t) + ω2 y (t) = ω2 u (t)
                      n          n

To solve the above in Matlab using ode45, the differential equation is converted to 2 first order ODE’s as was done before resulting in

[x ′]   [  0      1   ][x1 ]   [ 0 ]
   1′  =     2                +    2 u (t)
  x2     − ωn  − 2ζωn    x2     ωn

For a step input, u (t) = 1  , we obtain

[x′]   [  0      1   ] [x1]   [ 0 ]
  1′  =      2               +    2
 x2      − ω n − 2 ζωn  x2     ω n

Now ODE45 can be used. In Mathematica the differential equation is solved directly using DSolve and no conversion is needed.

Mathematica

pict

Matlab

pict

1.37  Plot the dynamic response factor Rd  of a system as a function of r = -ω
    ωn   for different damping ratios

Problem: Plot the standard curves showing how the dynamic response Rd  changes as      ω-
r =  ωn   changes. Do this for different damping ratio ξ  . Also plot the phase angle.

These plots are result of analysis of the response of a second order damped system to a harmonic loading. ω  is the forcing frequency and ωn  is the natural frequency of the system.



Mathematica

pict



pict



 

1.38  How to find closed loop step response to a plant with a PID controller?

Find and plot the step response of the plant --1----
s2+2s+1   connected to a PID controller with P  = 10,I = 3.7,D  = 0.7  . Use negative closed loopback.



Mathematica

pict



 


Matlab

pict



 

1.39  How to make Nyquist plot?

Nyquist command takes as input the open loop transfer function (not the closed loop!) and generates a plot, which was can look at to determine if the closed loop is stable or not. The closed loop is assumed to be unity feedback. For example, if the open loop is G (s)  , then we know that the closed loop transfer function is 1+GG(s)(s)-   . But we call Nyquist with G (s)  .

Here are two examples.

1.39.1  Example 1

Given G(s) =  --s--
        1− 0.2s  generate Nyquist plot.



Mathematica

pict



 


Matlab

pict



 

1.39.2  Example 2

Given         ---5(1−0.5s)----
G(s) =  s(1+0.1s)(1−0.25s)   generate Nyquist plot.



Mathematica

pict



 


Matlab

 
 
         2.5 s - 5 
  ------------------------ 
  0.025 s^3 + 0.15 s^2 - s 
 
Continuous-time transfer function.



pict



 

However, there is a better function to do this called nyquist1.m which I downloaded and tried. Here is its results



pict



 

2  Linear algebra, Linear solvers, common operations on vectors and matrices

 2.1  Multiply matrix with a vector
 2.2  Insert a number at specific position in a vector or list
 2.3  Insert a row into a matrix
 2.4  Insert a column into a matrix
 2.5  Build matrix from other matrices and vectors
 2.6  Generate a random 2D matrix from uniform (0 to 1) and from normal distributions
 2.7  Generate an n by m zero matrix
 2.8  Rotate a matrix by 90 degrees
 2.9  Generate a diagonal matrix with given values on the diagonal
 2.10  Sum elements in a matrix along the diagonal
 2.11  Find the product of elements in a matrix along the diagonal
 2.12  Check if a Matrix is diagonal
 2.13  Find all positions of elements in a Matrix that are larger than some value
 2.14  Replicate a matrix
 2.15  Find the location of the maximum value in a matrix
 2.16  Swap 2 columns in a matrix
 2.17  Join 2 matrices side-by-side and on top of each others
 2.18  Copy the lower triangle to the upper triangle of a matrix to make symmetric matrix
 2.19  extract values from matrix given their index
 2.20  Convert N  by M  matrix to a row of length N M
 2.21  find rows in a matrix based on values in different columns
 2.22  Select entries in one column based on a condition in another column
 2.23  Locate rows in a matrix with column being a string
 2.24  Remove set of rows and columns from a matrix at once
 2.25  Convert list of separated numerical numbers to strings
 2.26  Obtain elements that are common to two vectors
 2.27  Sort each column (on its own) in a matrix
 2.28  Sort each row (on its own) in a matrix
 2.29  Sort a matrix row-wise using first column as key
 2.30  Sort a matrix row-wise using non-first column as key
 2.31  Replace the first nonzero element in each row in a matrix by some value
 2.32  Perform outer product and outer sum between two vector
 2.33  Find the rank and the bases of the Null space for a matrix A
 2.34  Find the singular value decomposition (SVD) of a matrix
 2.35  Solve Ax =  b
 2.36  Find all nonzero elements in a matrix
 2.37  evaluate f(x) on a vector of values
 2.38  generates equally spaced N points between x1   and x2
 2.39  evaluate and plot a f (x,y)  on 2D grid of coordinates
 2.40  Find determinant of matrix
 2.41  Generate sparse matrix with n  by n  matrix repeated on its diagonal
 2.42  Generate sparse matrix for the tridiagonal representation of second difference operator in 1D
 2.43  Generate sparse matrix for the Laplacian differential operator ∇2u  for 2D grid
 2.44  Generate sparse matrix for the Laplacian differential operator ∇2u  for 3D grid
 2.45  Generate the adjugate matrix for square matrix
 2.46  Multiply each column by values taken from a row
 2.47  extract submatrix from a larger matrix by removing row/column
 2.48  delete one row from a matrix
 2.49  delete one column from a matrix
 2.50  generate random matrix so that each row adds to 1
 2.51  generate random matrix so that each column adds to 1
 2.52  sum all rows in a matrix
 2.53  sum all columns in a matrix
 2.54  find in which columns values that are not zero
 2.55  How to remove values from one vector that exist in another vector
 2.56  How to find mean of equal sized segments of a vector
 2.57  find first value in column larger than some value and cut matrix from there
 2.58  make copies of each value into matrix into a larger matrix
 2.59  repeat each column of matrix number of times
 2.60  How to apply a function to each value in a matrix?
 2.61  How to sum all numbers in a list (vector)?
 2.62  How to find maximum of each row of a matrix?
 2.63  How to find maximum of each column of a matrix?
 2.64  How to add the mean of each column of a matrix from each column?
 2.65  How to add the mean of each row of a matrix from each row?
 2.66  Find the different norms of a vector
 2.67  Check if a matrix is Hermite
 2.68  Obtain the LU decomposition of a matrix
 2.69  Linear convolution of 2 sequences
 2.70  Circular convolution of two sequences
 2.71  Linear convolution of 2 sequences with origin at arbitrary position
 2.72  Visualize a 2D matrix
 2.73  Find the cross correlation between two sequences
 2.74  Find orthonormal vectors that span the range of matrix A
 2.75  Solve A x= b and display the solution
 2.76  Determine if a set of linear equations A x= b, has a solution and what type of solution
 2.77  Given a set of linear equations automatically generate the matrix A  and vector b  and solve Ax = b
 2.78  Convert a matrix to row echelon form and to reduced row echelon form
 2.79  Convert 2D matrix to show the location and values

Mathematica and Matlab allow one to do pretty much the same operations in the area of linear algebra and matrix manipulation. Two things to keep in mind is that Mathematica uses a more general way to store data.

Mathematica uses ragged arrays or a list of lists. This means rows can have different sizes. (these are the lists inside the list). So a Mathematica matrix is stored in a list of lists. This is similar in a way to Matlab cell data structure, since each raw can have different length. In a standard matrix each row must have the same length.

In Matlab one can also have ragged arrays, these are called cells. In Mathematica, there is one data structure for both.

Another thing to keep in mind is that Matlab, due to its Fortran background is column major when it comes to operations on matrices. This simple example illustrate this difference. Suppose we have a matrix A  of 3 rows, and want to find the location where A (i,j) = 2  where i  is the row number and j  is the column number. Given this matrix

     (             )
        1  2  3  4
A =  (  2  3  1  5 )

        5  6  7  2

Then the result of using the find() command in Matlab is

 
I = 
     2 
     1 
     3 
J = 
     1 
     2 
     4 
     s*(4 + s)*(6 + s)}, s]

The Matlab result gives the order of the rows it found the element at based on searching column wise since it lists the second row first in its result. Compare this to Mathematica Position[] command

which gives

 
{{1,2}, 
 {2,1}, 
 {3,4}}

Mathematica searched row-wise.

Mathematica use for matrix manipulate takes more time to master compared to Matlab, since Mathematica data structure is more general and little more complex (ragged arrays) compared to Matlab’s since Mathematica also has to support symbolics in its commands and not just numbers

In Maple the following short cuts can be used enter vectors and matrices: For row vector:  v:=<1|2|3|4> and for column vector  v:=<1,2,3,4> and for matrix of say 2 rows and 3 columns  A:=<1,2|3,4|5,6> so | acts as column separator. There are other ways to do this (as typical in Maple), but I find the above the least confusing. For transpose  A^%T can be used.

2.1  Multiply matrix with a vector

How to perform the following matrix/vector multiplication?

 
[ 1 2 3 ]   [ 1 ] 
[ 4 5 6 ] * [ 2 ] 
[ 7 8 8 ]   [ 3 ]

In Mathematica the dot "." is used for Matrix multiplication. In Matlab the "*" is used. In Fortran, MATMUL is used.



Mathematica

 
Out[7]= {14,32,47}



 


Matlab

 
    14 
    32 
    50



 

Ada

compile and run

 
>gnatmake -gnat2012 t1.adb 
gcc -c -gnat2012 t1.adb 
gnatbind -x t1.ali 
gnatlink t1.ali 
>./t1 
 1.40000E+01 
 3.20000E+01 
 5.00000E+01

Fortran

compile and run

 
>gfortran  -fcheck=all -Wall -Wconversion 
   -Wextra -Wconversion-extra -pedantic test.f90 
>./a.out 
14.000000000000000  32.000000000000000 50.000000000000000 
 number of rows =            3 
 number of columns =            1


Maple

⌊  ⌋
 14
⌈32⌉

 50



 


Python

 
array([[14], 
       [32], 
       [47]])



 

2.2  Insert a number at specific position in a vector or list

The problem is to insert a number into a vector given the index.



Mathematica

 
Out[11]= {1,2,99,3,4}



 


Matlab

 
A = 
     1     2    99     3     4



 


Fortran

 
>gfortran -std=f2008 t2.f90 
>./a.out 
 1.0000000 2.0000000 99.000000 
          3.0000000 4.0000000



 


Maple

Using <> notation

 
v :=[ 1 2 99 3 4]



 


Python

Python uses zero index.

 
   Out[86]: array([ 1,  2, 99,  3,  4])



 

2.3  Insert a row into a matrix

The problem is to insert a row into the second row position in a 2D matrix



Mathematica

 
 {{1,2,3}, 
  {90,91,92}, 
  {4,5,6}, 
  {7,8,9}}



 


Matlab

 
     1     2     3 
    90    91    92 
     4     5     6 
     7     8     9



 


Maple

Using <<>> notation

Using Matrix/Vector

 
[ 1  2   3 
  4  5   6 
  90 91  92 
  7  8   9]



 


Python

 
array([[ 1,  2,  3], 
       [90, 91, 92], 
       [ 4,  5,  6], 
       [ 7,  8,  9]])



 


Fortran

Compile and run

 
>gfortran -std=f2008 t3.f90 
>./a.out 
 before 
 1           2           3 
 4           5           6 
 7           8           9 
 after 
 1           2           3 
 90          91          92 
 4           7           5 
 8           6           9



 

2.4  Insert a column into a matrix

The problem is to insert a column into the second column position in a 2D matrix.



Mathematica

 
 {{1,90,2,3}, 
  {4,91,5,6}, 
  {7,92,8,9}}



 


Matlab

 
     1    90     2     3 
     4    91     5     6 
     7    92     8     9



 


Fortran

 
>gfortran t4.f90 
>./a.out 
 1          90           2           3 
 4          91           5           6 
 7          92           8           9



 


Maple

Using Matrix/Vector

 
[ 1    90     2     3 
  4    91     5     6 
  7    92     8     9]



 


Python

 
array([[ 1, 90,  2,  3], 
       [ 4, 91,  5,  6], 
       [ 7, 92,  8,  9]])



 

2.5  Build matrix from other matrices and vectors

2.5.1  First example

Given column vectors      ⌊    ⌋
        1
v1 = ⌈  2 ⌉
        3 and      ⌊    ⌋
        4
v2 = ⌈  5 ⌉
        6 and      ⌊    ⌋
        7
v3 = ⌈  8 ⌉
        9 and      ⌊     ⌋
        10
v4 = ⌈  11 ⌉
        12 generate the matrix                    ⌊       ⌋
                     1   4
                   || 2   5 ||
                   |       |
     [ v   v  ]    || 3   6 ||
m  =     1  2   =  ||       ||
       v3  v4      | 7  10 |
                   ||       ||
                   ⌈ 8  11 ⌉
                     9  12

Matlab was the easiest of all to do these operations with. No surprise, as Matlab was designed for Matrix and vector operations. But I was surprised that Maple actually had good support for these things, using its <> notation, which makes working with matrices and vectors much easier.

The command ArrayFlatten is essential for this in Mathematica.

Notice the need to use Transpose[{v}] in order to convert it to a column matrix. This is needed since in Mathematica, a list can be a row or column, depending on context.



Mathematica

(     )
  1 4
|| 2 5 ||
| 3 6 |
|| 710 ||
|(     |)
  811
  912



 


Matlab

 
m = 
     1     4 
     2     5 
     3     6 
     7    10 
     8    11 
     9    12



 


Maple

⌊ 1 4⌋
|    |
| 2 5|
||    ||
|| 3 6||
|    |
|| 710||
| 811|
⌈    ⌉
  912



 


Python

Another way

 
Out[211]: 
array([[ 1,  4], 
       [ 2,  5], 
       [ 3,  6], 
       [ 7, 10], 
       [ 8, 11], 
       [ 9, 12]])



 


Fortran

Using the RESHAPE command

 
>gfortran -Wall foo.f90 
>./a.out 
1           4 
2           5 
3           6 
7          10 
8          11 
9          12



 

2.5.2  second example

Given mix of matrices and vectors, such as      ⌊    ⌋
        1
v1 = ⌈  2 ⌉
        3 and      ⌊      ⌋
       4  5
v2 = ⌈ 6  7 ⌉
       8  9 and      ⌊    ⌋
       10
v3 = ⌈ 11 ⌉
       12 and      ⌊     ⌋
       13
v4 = ⌈ 14  ⌉
       15 and

      ⌊ 16 ⌋
      ⌈    ⌉
v5 =    17
        18

generate the matrix 6 by 3 matrix                        ⌊             ⌋
                          1    4   5
                       |             |
                       ||  2    6   7 ||
     [             ]   |             |
m  =    v1  v2       = ||  3    8   9 ||
        v3  v4  v5     ||  10  13  16 ||
                       |             |
                       |⌈  11  14  17 |⌉

                          12  15  18

Mathematica, thanks for function by Kuba at Mathematica stackexachage, this becomes easy to do

Mathematica

Maple

Matlab

Fortran

 
>gfortran -Wall foo.f90 
>./a.out 
           1           4           5 
           2           6           7 
           3           8           9 
          10          13          16 
          11          14          17 
          12          15          18

2.6  Generate a random 2D matrix from uniform (0 to 1) and from normal distributions



Mathematica

 
 {{0.100843,0.356115,0.700317,0.657852}, 
  {0.238019,0.59598,0.523526,0.576362}, 
  {0.339828,0.32922,0.0632487,0.815892}}



 
{{-0.226424,1.19553,0.601433,1.28032}, 
{1.66596,0.176225,-0.619644,0.371884}, 
{0.895414,-0.394081,0.153507,-1.74643}}



 


Matlab

 
mat = 
 0.6787    0.3922    0.7060    0.0462 
 0.7577    0.6555    0.0318    0.0971 
 0.7431    0.1712    0.2769    0.8235



 
mat = 
 0.3252   -1.7115    0.3192   -0.0301 
-0.7549   -0.1022    0.3129   -0.1649 
 1.3703   -0.2414   -0.8649    0.6277



 


Maple

 
[[0.93,0.66,0.92,0.80], 
 [0.85,0.96,0.42,0.49], 
 [0.04,0.79,0.14,0.96] 
]



 

Or

⌊                                                                                                 ⌋
  0.970592781760615697    0.957506835434297598    0.0975404049994095246    0.126986816293506055
||                                                                                                 ||
⌈ 0.157613081677548283    0.546881519204983846    0.632359246225409510     0.905791937075619225   ⌉
  0.964888535199276531    0.278498218867048397    0.913375856139019393     0.814723686393178936

Fortran

 
>gfortran -Wall -std=f2008 t5.f90 
>./a.out 
 from uniform distribution 
  0.99755955      0.74792767      7.37542510E-02 
  0.56682467      0.36739087      5.35517931E-03 
  0.96591532      0.48063689      0.34708124 
 
 from normal distribution 
 -4.70122509E-02  0.74792767      7.37542510E-02 
  0.56682467      5.17370142E-02  5.35517931E-03 
  0.96591532      0.48063689      0.34708124

Did not find a build-in support for random numbers from normal distribution, need to look more.

2.7  Generate an n by m zero matrix



Mathematica

 
    {{0,0,0,0}, 
     {0,0,0,0}, 
     {0,0,0,0}}



 


Matlab

 
A = 
     0     0     0     0 
     0     0     0     0 
     0     0     0     0



 


Maple

⌊     ⌋
 0000
⌈0000 ⌉
 0000



 

2.8  Rotate a matrix by 90 degrees



Mathematica

 
    {{3,6,9}, 
     {2,5,8}, 
     {1,4,7}}



 


Matlab

 
     3     6     9 
     2     5     8 
     1     4     7



 


Maple

 
[[3,2,1], 
 [6,5,4], 
 [9,8,7]]



 
   [[3,6,9], 
    [2,5,8], 
    [1,4,7]]



 

2.9  Generate a diagonal matrix with given values on the diagonal

Problem: generate diagonal matrix with 2,4,6,8  on the diagonal.



Mathematica

 
     {{2,0,0,0}, 
      {0,4,0,0}, 
      {0,0,6,0}, 
      {0,0,0,8}}



 


Matlab

 
     2     0     0     0 
     0     4     0     0 
     0     0     6     0 
     0     0     0     8



 


Maple

 
[[2,0,0,0], 
 [0,4,0,0], 
 [0,0,6,0], 
 [0,0,0,8]]



 

2.10  Sum elements in a matrix along the diagonal



Mathematica

 
Out[45]= 15



 


Matlab

 
ans = 
    15



 


Maple

Another ways

15



 

2.11  Find the product of elements in a matrix along the diagonal



Mathematica

Out[49]= 45



 


Matlab

ans = 45



 


Maple

45



 

2.12  Check if a Matrix is diagonal

A diagonal matrix is one which has only zero elements off the diagonal. The Mathematica code was contributed by Jon McLoone.



Mathematica

 
  Out[59]= False 
  Out[60]= True 
  Out[61]= False



 


Maple

true



 

2.13  Find all positions of elements in a Matrix that are larger than some value

The problem is to find locations or positions of all elements in a matrix that are larger or equal than some numerical value such as 2  in this example.



Mathematica

 
   {{1,2},{1,3},{2,1},{3,1}}



 


Matlab

 
I = 
     2 
     3 
     1 
     1 
J = 
     1 
     1 
     2 
     3



 


Maple

 
 [2, 1], [3, 1], [1, 2], [1, 3]



 

2.14  Replicate a matrix

Given Matrix

 
     1     2 
     3     4

Generate a new matrix of size 2  by 3  where each element of the new matrix is the above matrix. Hence the new matrix will look like

 
     1     2     1     2     1     2 
     3     4     3     4     3     4 
     1     2     1     2     1     2 
     3     4     3     4     3     4

In Matlab, repmat() is used. In Mathematica, a Table command is used, followed by ArrayFlatten[]



Mathematica

 
  {{1,2,1,2,1,2}, 
   {3,4,3,4,3,4}, 
   {1,2,1,2,1,2}, 
   {3,4,3,4,3,4}}



 


Matlab

 
ans = 
     1     2     1     2     1     2 
     3     4     3     4     3     4 
     1     2     1     2     1     2 
     3     4     3     4     3     4



 

Another way is to use kron() in matlab, and KroneckerProduct in Mathematica and LinearAlgebra[KroneckerProduct] in Maple, which I think is a better way. As follows



Mathematica

 
  {{1,2,1,2,1,2}, 
   {3,4,3,4,3,4}, 
   {1,2,1,2,1,2}, 
   {3,4,3,4,3,4}}



 


Matlab

 
ans = 
     1     2     1     2     1     2 
     3     4     3     4     3     4 
     1     2     1     2     1     2 
     3     4     3     4     3     4



 


Maple

 
[[1,2,1,2,1,2], 
 [3,4,3,4,3,4], 
 [1,2,1,2,1,2], 
 [3,4,3,4,3,4]]



 

2.15  Find the location of the maximum value in a matrix



Mathematica

 
Out[142]= {{2,2},{3,3}}



 


Matlab

 
r = 
     2 
     3 
c = 
     2 
     3



 


Maple

This below finds position of first max.

 
     3,3



Maple support for such operations seems to be not as strong as Matlab. One way to find locations of all elements is by using explicit loop

 
    [[2, 2], [3, 3]]



 

2.16  Swap 2 columns in a matrix

Give a matrix

 
     1     2 
     3     4 
     5     6

How to change it so that the second column becomes the first, and the first becomes the second? so that the result become

 
     2     1 
     4     3 
     6     5


Mathematica

 
Out[29]= {{2, 1}, 
          {4, 3}, 
          {6, 5}}



 


Matlab

 
     2     1 
     4     3 
     6     5



 


Maple

 
   [[2,1], 
    [4,3], 
    [6,5]]



 

2.17  Join 2 matrices side-by-side and on top of each others



Mathematica

In Mathematica, to join 2 matrices side-by-side, use Join with '2' as the third argument. To join them one on top of the other, use '1' as the third argument

 
Out[146]= {{8,5, 1}, 
           {8,10,8}, 
           {6,0, 8}}



 
 {{9, 0,1}, 
 {10,2,7}, 
 {8, 0,8}}



 
 {{8,5, 1, 9,0,1}, 
 {8,10,8,10,2,7}, 
 {6,0, 8, 8,0,8}}



 
 {{8, 5 , 1}, 
 {8, 10, 8}, 
 {6, 0 , 8}, 
 {9, 0 , 1}, 
 {10,2 , 7}, 
 {8, 0 , 8}}



 


Matlab

 
 0.5472 0.2575 0.8143 0.3500 0.6160 0.8308 
 0.1386 0.8407 0.2435 0.1966 0.4733 0.5853 
 0.1493 0.2543 0.9293 0.2511 0.3517 0.5497



 
    0.5472    0.2575    0.8143 
    0.1386    0.8407    0.2435 
    0.1493    0.2543    0.9293 
    0.3500    0.6160    0.8308 
    0.1966    0.4733    0.5853 
    0.2511    0.3517    0.5497



 


Maple



 

2.18  Copy the lower triangle to the upper triangle of a matrix to make symmetric matrix

Question posted on the net

 
please help me with simple to apply function that will construct 
symmetric matrix from given just a half matrix with diagonal. 
Eg: 
 
From: 
1  0  0  0 
2  3  0  0 
4  9  5  0 
2  2  3  4 
 
To give: 
 
1  2  4  2 
2  3  9  2 
4  9  5  3 
2  2  3  4

Many answers were given, below is my answer, and I also show how to do it in Matlab



Mathematica

 
 {{1, 2, 4, 2}, 
  {2, 3, 9, 2}, 
  {4, 9, 5, 3}, 
  {2, 2, 3, 4} 
 }



 


Matlab

 
ans = 
     1     2     4     2 
     2     3     9     2 
     4     9     5     3 
     2     2     3     4



 


Maple

 
     [[1,2,4,2], 
      [2,3,9,2], 
      [4,9,5,3], 
      [2,2,3,4]]



 

2.19  extract values from matrix given their index

Given a matrix A, and list of locations within the matrix, where each location is given by i,j  entry, find the value in the matrix at these locations

Example, given

 
A={{1,2,3}, 
   {4,5,6}, 
   {7,8,9}}

obtain the entries at 1,1  and 3,3  which will be 1  and 9  in this example.



Mathematica

 
   {1,9}



Another method (same really as above, but using Part explicit)

 
{1,9}



 


Matlab

 
ans = 
     1     9



 


Maple

 
    [1, 9]



 

2.20  Convert N  by M  matrix to a row of length N M

Given

 
a=[1 2 3 
   4 5 6 
   7 8 9]

covert the matrix to one vector

 
[1 2 3 4 5 6 7 8 9]


Mathematica

 
{1,2,3,4,5,6,7,8,9}



 


Matlab

 
 1 4 7 2 5 8 3 6 9



 


Maple

Maple reshapes along columns, like Matlab. To get same result as Mathematica, we can transpose the matrix first. To get same result as Matlab, do not transpose.

Notice the result is a row matrix and not a vector. To get a vector

They look the same on the screen, but using whattype we can find the type.

 
[[1,2,3,4,5,6,7,8,9]]



 

2.21  find rows in a matrix based on values in different columns

Example, given Matrix

 
     1     9     0    10 
     5     6     7     8 
     3     9     2    10

Select rows which has 9  in the second column and 10  in the last column. Hence the result will be the first and third rows only

 
      1     9     0    10 
      3     9     2    10


Mathematica

 
{{1},{3}}



 
 {{1,9,0,10}, 
  {3,9,2,10}}



 


Matlab

 
ans = 
     1     9     0    10 
     3     9     2    10



 


Maple

 
[[1,9,0,10], 
 [3,9,2,10]]



 

2.22  Select entries in one column based on a condition in another column

Given

 
A=[4  3 
   6  4  ----> 
   7  6  ----> 
   2  1 
   1  3 
   9  2 
   2  5  ----> 
   1  2 
   ]

Select elements in the first column only which has corresponding element in the second column greater than 3, hence the result will be

 
     [6 7 2]


Mathematica

 
      {6, 7, 2}



another way is to find the index using Position and then use Extract

 
    {6, 7, 2}



another way is to use Cases[]. This is the shortest way

 
    {6, 7, 2}



 


Matlab

 
     6 
     7 
     2



 


Maple

 
[[6], 
 [7], 
 [2]]



 

2.23  Locate rows in a matrix with column being a string

The problem is to select rows in a matrix based on string value in the first column. Then sum the total in the corresponding entries in the second column. Given. For example, given

 
mat = {'foobar', 77; 
       'faabar', 81; 
       'foobur', 22; 
       'faabaa', 8; 
       'faabian', 88; 
       'foobar', 27; 
       'fiijii', 52};

and given list

 
{'foo', 'faa'}

The problem is to select rows in which the string in the list is part of the string in the first column in the matrix, and then sum the total in the second column for each row found. Hence the result of the above should be

 
    'foo'    'faa' 
    [126]    [ 177]


Mathematica

 
{{"foo", 126}, {"faa", 177}}



 


Matlab

 
ans = 
    'foo'    'faa' 
    [126]    [177]



But notice that in Matlab, the answer is a cellarray. To access the numbers above

 
ans = 
    'foo'    [126] 
ans = 
    'faa'    [177] 
 
ans = 
   126 
 
ans = 
    177



 

2.24  Remove set of rows and columns from a matrix at once

Given: square matrix, and list which represents the index of rows to be removed, and it also represents at the same time the index of the columns to be removed (it is square matrix, so only one list is needed).

output: the square matrix, with BOTH the rows and the columns in the list removed.

Assume valid list of indices.

This is an example: remove the second and fourth rows and the second and fourth columns from a square matrix.

pict

I asked this question at SO, and more methods are shown there at HTML



Mathematica Three methods are shown.

method 1:

(credit for the idea to Mike Honeychurch at stackoverflow). It turns out it is easier to work with what we want to keep instead of what we want to delete so that Part[] can be used directly.

Hence, given a list of row numbers to remove, such as

 
pos = {2, 4};

Start by generating list of the rows and columns to keep by using the command Complement[], followed by using Part[]

 
{{0, 2, 1, 0}, 
 {4, 3, 3, 2}, 
 {3, 4, 3, 3}, 
 {5, 4, 2, 0} 
}



method 2: (due to Mr Wizard at stackoverflow)

 
{{0, 2, 1, 0}, 
 {4, 3, 3, 2}, 
 {3, 4, 3, 3}, 
 {5, 4, 2, 0} 
}



method 3: (me)

use Pick. This works similar to Fortran pack(). Using a mask matrix, we set the entry in the mask to False for those elements we want removed. Hence this method is just a matter of making a mask matrix and then using it in the Pick[] command.

 
Out[39]= {{0,2,1,0}, 
          {4,3,3,2}, 
          {3,4,3,3}, 
          {5,4,2,0}}



 


Matlab

 
a = 
     0     2     1     0 
     4     3     3     2 
     3     4     3     3 
     5     4     2     0



 

2.25  Convert list of separated numerical numbers to strings

Problem: given a list of numbers such as

 
{{1, 2}, 
 {5, 3, 7}, 
 {4} 
 }

convert the above to list of strings

 
{"12", 
 "537", 
 "4"}


Mathematica

 
List["12","537","4"]



 


Matlab

 
ans = 
    '1  2' 
    '5  3  7' 
    '4'



answer below is due to Bruno Luong at Matlab newsgroup

 
    '12'    '537'    '4'



 

2.26  Obtain elements that are common to two vectors

Given vector or list d = [− 9, 1,3,− 3,50,7,19],  t = [0,7,2, 50]  , find the common elements.



Mathematica

 
Out[412]= {7,50}



 


Matlab

 
ans = 
     7    50



 

2.27  Sort each column (on its own) in a matrix

Given

 
     4     2     5 
     2     7     9 
    10     1     2

Sort each column on its own, so that the result is

 
     2     1     2 
     4     2     5 
    10     7     9

In Matlab, the sort command is used. But in the Mathematica, the Sort command is the same the Matlab’s sortrows() command, hence it can’t be used as is. Map is used with Sort to accomplish this.



Mathematica

 
{{2, 1, 2}, 
 {4, 2, 5}, 
 {10,7, 9}}



 


Matlab

 
     2     1     2 
     4     2     5 
    10     7     9



 

2.28  Sort each row (on its own) in a matrix

Given

 
     4     2     5 
     2     7     9 
    10     1     2

Sort each row on its own, so that the result is

 
     2     4     5 
     2     7     9 
     1     2     10


Mathematica

 
{{2, 4, 5}, 
{2, 7, 9}, 
{1, 2, 10}}



 


Matlab

 
     2     4     5 
     2     7     9 
     1     2    10



 

2.29  Sort a matrix row-wise using first column as key

Given

 
     4     2     5 
     2     7     9 
    10     1     2

Sort the matrix row-wise using first column as key so that the result is

 
     2     7     9 
     4     2     5 
    10     1     2

In Matlab, the sortrows() command is used. In Mathematica the Sort[] command is now used as is.



Mathematica

 
{{2,  7, 9}, 
{4,  2, 5}, 
{10, 1, 2}}



 


Matlab

 
     2     7     9 
     4     2     5 
    10     1     2



 

2.30  Sort a matrix row-wise using non-first column as key

Given

 
     4     2     5 
     2     7     9 
    10     1     2

Sort the matrix row-wise using the second column as key so that the result is

 
    10     1     2 
     4     2     5 
     2     7     9

In Matlab, the sortrows() command is used, but now we tell it to use the second column as key.

In Mathematica the SortBy[] command is now used but we tell it to use the second slot as key.



Mathematica

 
{{10, 1, 2}, 
{4,  2, 5}, 
{2,  7, 9}}



 


Matlab

 
    10     1     2 
     4     2     5 
     2     7     9



 

2.31  Replace the first nonzero element in each row in a matrix by some value

Problem: Given a matrix, replace the first nonzero element in each row by some a specific value. This is an example. Given matrix A  below, replace the first non-zero element in each row by − 1  , then

     (              )
       50   75   0
     || 50   0   100 ||
     | 0    75  100 |
A  = || 75  100   0  ||
     |(              |)
       0    75  100
       0    75  100 will become      (              )
       − 1  75    0
     || − 1   0   100||
     |  0   − 1  100|
B  = || − 1  100   0 ||
     |(              |)
        0   − 1  100
        0   − 1  100



Mathematica

Solution due to Bob Hanlon (from Mathematica newsgroup)

Solution by Fred Simons (from Mathematica newsgroup)

Solution due to Adriano Pascoletti (from Mathematica newsgroup)

Solution due to Oliver Ruebenkoenig (from Mathematica newsgroup)

Solution due to Szabolcs Horvát (from Mathematica newsgroup)

 
{{-1,75,0},{-1,0,100},{0,-1,100}, 
{-1,100,0},{0,-1,100},{0,-1,100}}



 


Matlab

This solution due to Bruno Luong (from matlab newsgroup)

This solution due to Jos from matlab newsgroup

 
A = 
    -1    75     0 
    -1     0   100 
     0    -1   100 
    -1   100     0 
     0    -1   100 
     0    -1   100



 

2.32  Perform outer product and outer sum between two vector

Problem: Given 2 vectors, perform outer product and outer sum between them. The outer operation takes the first element in one vector and performs this operation on each element in the second vector. This results in first row. This is repeated for each of the elements in the first vector. The operation to perform can be any valid operation on these elements.



Mathematica

using symbolic vectors. Outer product

 
{{a e, a f, a g}, 
{b e, b f, b g}, 
{c e, c f, c g}}



Outer sum

 
{{a+e, a+f, a+g}, 
{b+e, b+f, b+g}, 
{c+e, c+f, c+g}}



using numerical vectors. Outer product

 
{{4,  5,  6}, 
{8,  10, 12}, 
{12, 15, 18}}



Outer sum

 
  {{5, 6, 7}, 
   {6, 7, 8}, 
   {7, 8, 9}}



 


Matlab

Outer product

 
ans = 
     4     5     6 
     8    10    12 
    12    15    18



Outer sum

 
ans = 
     5     6     7 
     6     7     8 
     7     8     9



 


Maple

Due to Carl Love from the Maple newsgroup

 
[a*d,a*e,a*f,b*d, 
  b*e, b*f, c*d, c*e, c*f]



 
[a+d, a+e, a+f, b+d, 
  b+e, b+f, c+d, c+e, c+f]



 

2.33  Find the rank and the bases of the Null space for a matrix A

Problem: Find the rank and nullities of the following matrices, and find the bases of the range space and the Null space.

     (               )
       2   3    3   4
A  = ( 0  − 1  − 2  2)
       0   0    0   1



Mathematica

3,4



 
   Rank (or dimension of the range space)=3



 
   Dimension of the Null Space=1



 
Basis for Null Space={{3,-4,2,0}}



 


Matlab

 
A range space dimension=3 
A null space dimension= 1 
Basic for null space of A = 
 
ans = 
 1.5000   -2.0000  1.0000  0



 

2.34  Find the singular value decomposition (SVD) of a matrix

Problem: Find the SVD for the matrix [        ]
 1  2   3
 4  5   6 Notice that in Maple, the singular values matrix, normally called S, is returned as a column vector. So need to call DiagonalMatrix() to format it as expected.



Mathematica

 
{{0.386318,-0.922366}, 
{0.922366,0.386318}} 
 
{{9.50803,0.,0.}, 
{0.,0.77287,0.}} 
 
{{0.428667,0.805964,0.408248}, 
{0.566307,0.112382,-0.816497}, 
{0.703947,-0.581199,0.408248}}



 
{{1.,2.,3.}, 
{4.,5.,6.}}



 


Matlab

 
u = 
   -0.3863   -0.9224 
   -0.9224    0.3863 
 
s = 
 
    9.5080         0         0 
         0    0.7729         0 
 
v = 
 
   -0.4287    0.8060    0.4082 
   -0.5663    0.1124   -0.8165 
   -0.7039   -0.5812    0.4082



 
ans = 
    1.0000    2.0000    3.0000 
    4.0000    5.0000    6.0000



 


Maple

 
     [1    2    3 ] 
A := [            ] 
     [4    5    6.]



 
 [0.386317703118612    -0.922365780077058] 
 [                                       ] 
 [0.922365780077058    0.386317703118612 ]



 
     [9.50803200069572            0            0] 
s := [                                          ] 
     [       0            0.772869635673485    0] 
 
     [0.428667133548626    0.566306918848035     0.703946704147444 ] 
v:=  [0.805963908589298    0.112382414096594     -0.581199080396110] 
     [0.408248290463863    -0.816496580927726    0.408248290463863 ]



 
      [9.50803200069572        0            0] 
s2 := [                                      ] 
      [       0         0.772869635673485    0]



 
[1.    2.    3.] 
[              ] 
[4.    5.    6.]



 

2.35  Solve Ax  = b

Solve for x in the following system of equations

 
[ 1 2 3 ][x1]   [ 1 ] 
[ 7 5 6 ][x2]=  [ 2 ] 
[ 7 8 8 ][x3]   [ 3 ]


Mathematica

 
{0,0,1/3}



 


Matlab

 
ans = 
                   0 
                   0 
   0.333333333333333



 

Fortran

compile and run

 
$ gfortran -std=f2003 -Wextra -Wall -pedantic -funroll-loops 
  -ftree-vectorize -march=native  -Wsurprising -Wconversion 
  t2.f90  /usr/lib/liblapack.a /usr/lib/libblas.a 
 
$ ./a.exe 
 solution is 
 -5.28677630773884192E-018 -3.70074341541718826E-017  0.33333333333333337

2.36  Find all nonzero elements in a matrix

Given a matrix, find the locations and the values of all nonzero elements. Hence given the matrix

(           )
    0  0  1
(  10  0  2 )
    3  0  0

the positions returned will be (1,3),(2,1),(2,3),(3,1)  and the corresponding values are 1,10, 2,3  .



Mathematica

In Mathematica, standard Mathematica matrix operations can be used, or the matrix can be converted to SparseArray and special named operation can be used on it.

 
{{1,3},{2,1},{2,3},{3,1},{3,2}}



 
{1,10,2,3,4}



Or standard list operations can be used

 
{1,10,2,3,4}



 
{{1,3},{2,1},{2,3},{3,1},{3,2}}



 


Matlab

 
values = 
    10 
     3 
     4 
     1 
     2



 
I = 
     2 
     3 
     3 
     1 
     2 
J = 
     1 
     1 
     2 
     3 
     3



 

2.37  evaluate f(x) on a vector of values

Given a function f (x)  evaluate it for each value contained in a vector. For example, given f (x ) = x2   evaluate it on (1,2,3)  such that the result is (1,4,9)  .



Mathematica

 
{1,4,9}



 


Matlab

 
ans = 
     1     4     9



 

2.38  generates equally spaced N points between x1   and x2



Mathematica

 
x1=1; 
x2=3; 
FindDivisions[{x1,x2},5] 
 
Out[48]= {1,3/2,2,5/2,3} 
 
N[%] 
Out[49]= {1.,1.5,2.,2.5,3.}

Matlab

 
clear all; 
x1 = 1; 
x2 = 3; 
linspace(x1,x2,5) 
 
ans = 
 1.0000  1.5000  2.0000  2.5000  3.0000



2.39  evaluate and plot a f (x, y)  on 2D grid of coordinates

Evaluate        2  2
xexp −x −y   on 2D cartesian grid between x = − 2 ⋅⋅⋅2  and y = − 4 ⋅⋅⋅4  using h =  0.4  for grid spacing.

Mathematica

pict

The above can also be done using Plot3D

pict

I need to sort out the orientation difference between the two plots above.

Matlab

pict

2.40  Find determinant of matrix

Given a square matrix, find its determinant. In Mathematica, the Det[] command is used. In Matlab the det() command is used.



Mathematica

 
-0.317792605942287



 


Matlab

 
  -0.276653966272994



 

2.41  Generate sparse matrix with n  by n  matrix repeated on its diagonal

Given matrix (         )
  1  2  3
( 4  5  6 )

  7  8  9 , generate the following sparse matrix with this matrix on the diagonal

(                          )
  1  2  3  0  0  0  0  0  0
| 4  5  6  0  0  0  0  0  0|
|| 7  8  9  0  0  0  0  0  0||
||                          ||
| 0  0  0  1  2  3  0  0  0|
|| 0  0  0  4  5  6  0  0  0||
|| 0  0  0  7  8  9  0  0  0||
| 0  0  0  0  0  0  1  2  3|
|( 0  0  0  0  0  0  4  5  6|)

  0  0  0  0  0  0  7  8  9



Mathematica

(               )
  1.2.3.0 0 0 0 0 0
|| 4.5.6.0 0 0 0 0 0||
| 7.8.9.0 0 0 0 0 0|
|| 0 0 01.2.3.0 0 0||
|| 0 0 04.5.6.0 0 0||
||               ||
|| 0 0 07.8.9.0 0 0||
| 0 0 0 0 0 01.2.3.|
( 0 0 0 0 0 04.5.6.)
  0 0 0 0 0 07.8.9.



 


Matlab

 
ans = 
     1     0     0 
     0     1     0 
     0     0     1



 
ans = 
 1  2  3  0  0  0  0  0  0 
 4  5  6  0  0  0  0  0  0 
 7  8  9  0  0  0  0  0  0 
 0  0  0  1  2  3  0  0  0 
 0  0  0  4  5  6  0  0  0 
 0  0  0  7  8  9  0  0  0 
 0  0  0  0  0  0  1  2  3 
 0  0  0  0  0  0  4  5  6 
 0  0  0  0  0  0  7  8  9



 

2.42  Generate sparse matrix for the tridiagonal representation of second difference operator in 1D

The second derivative 2
ddxu2-   is approximated by ui−1−2hu2i+ui+1   where h  is the grid spacing. Generate the A  matrix that represent this operator for n = 4  where n  is the number of internal grid points on the line



Mathematica

(                         )
|−21 −12 01 00 00 00 00 00 00 00 00 00 |
|| 0 1 −2 1 0 0 0 0 0 0 0 0 ||
||| 0 0 1 −2 1 0 0 0 0 0 0 0 |||
|| 0 0 0 1 −2 1 0 0 0 0 0 0 ||
||| 00 00 00 00 10 −12 − 120 1 00 00 00 00 |||
|| 0 0 0 0 0 0 1 − 2 1 0 0 0 ||
||| 0 0 0 0 0 0 0 1 −2 1 0 0 |||
|( 0 0 0 0 0 0 0 0 1 −2 1 0 |)
  00 00 00 00 00 00 00 00 00 10 −12 1−2



 


Matlab

 
ans = 
-2  1  0  0  0  0  0  0  0  0  0   0 
 1 -2  1  0  0  0  0  0  0  0  0   0 
 0  1 -2  1  0  0  0  0  0  0  0   0 
 0  0  1 -2  1  0  0  0  0  0  0   0 
 0  0  0  1 -2  1  0  0  0  0  0   0 
 0  0  0  0  1 -2  1  0  0  0  0   0 
 0  0  0  0  0  1 -2  1  0  0  0   0 
 0  0  0  0  0  0  1 -2  1  0  0   0 
 0  0  0  0  0  0  0  1 -2  1  0   0 
 0  0  0  0  0  0  0  0  1 -2  1   0 
 0  0  0  0  0  0  0  0  0  1 -2   1 
 0  0  0  0  0  0  0  0  0  0  1  -2



 

2.43  Generate sparse matrix for the Laplacian differential operator ∇2u  for 2D grid

∇2u  = f  in 2D is defined as ∂2u+  ∂2u=  f
∂x2   ∂y2  and the Laplacian operator using second order standard differences results in (                           )
  ui−1,j+ui+1,j+uih,j2−1+ui,j+1−4ui,j- =  fi,j  where h  is the grid size. The above is solved for x  in the form Ax  = f  by generating the A  matrix and taking into consideration the boundary conditions. The follows show how to generate the sparse representation of A  . Assuminh the number of unknowns n = 3  in one direction. Hence there are 9 unknowns to solve for and the A  matrix will be 9  by 9  .



Mathematica

(                        )
 − 4 1  0 1  0  0 0  0  0
|| 1 − 4 1 0  1  0 0  0  0||
|| 0  1 − 4 1 0  1 0  0  0||
|| 1  0  1 − 4 1 0 1  0  0||
|| 0  1  0 1 − 4 1 0  1  0||
|| 0  0  1 0  1 − 4 1 0  1||
| 0  0  0 1  0  1 − 4 1 0|
|( 0  0  0 0  1  0 1 − 4 1|)

  0  0  0 0  0  1 0  1 − 4



 


Matlab

 
ans = 
 -4  1  0  1  0  0  0  0  0 
  1 -4  1  0  1  0  0  0  0 
  0  1 -4  0  0  1  0  0  0 
  1  0  0 -4  1  0  1  0  0 
  0  1  0  1 -4  1  0  1  0 
  0  0  1  0  1 -4  0  0  1 
  0  0  0  1  0  0 -4  1  0 
  0  0  0  0  1  0  1 -4  1 
  0  0  0  0  0  1  0  1 -4



 

2.44  Generate sparse matrix for the Laplacian differential operator ∇2u  for 3D grid

The goal is to solve

∂2u    ∂2u    ∂2u
---2 + --2-+  --2-= − f(x, y,z)
∂x     ∂y     ∂z

On the unit cube. The following diagram was made to help setting up the 3D scheme to approximate the above PDE

pict

The discrete approximation to the Laplacian in 3D is

∂2u   ∂2u    ∂2u     1
--2-+ ---2 + ---2 = -2-(Ui−1,j,k + Ui+1,j,k + Ui,j−1,k + Ui,j+1,k + Ui,k,k− 1 + Ui,j,k+1 − 6Ui,j,k)
∂x    ∂y     ∂z     h

For the direct solver, the A  matrix needs to be formulated. From

-1-(Ui−1,j,k + Ui+1,j,k + Ui,j−1,k + Ui,j+1,k + Ui,k,k−1 + Ui,j,k+1 − 6Ui,j,k) = fi,j,k
h2

Solving for Ui,j,k  results in

        1(                                                                )
Ui,j,k =  --Ui −1,j,k + Ui+1,j,k + Ui,j−1,k + Ui,j+1,k + Ui,k,k−1 + Ui,j,k+1 − h2fi,j,k
        6

To help make the A  matrix, a small example with n = 2,  is made. The following diagram uses the standard numbering on each node

pict

By traversing the grid, left to right, then inwards into the paper, then upwards, the following A  matrix results

pict

The recursive pattern involved in these A  matrices can now be seen. Each A  matrix contains inside it a block on its diagonal which repeats n  times. Each block in turn contain inside it, on its diagonal, smaller block, which also repeats n  times.

It is easier to see the pattern of building A  by using numbers for the grid points, and label them in the same order as they would be visited, this allowes seeing the connection between each grid point to the other easier. For example, for n =  2  ,

pict

The connections are now more easily seen. Grid point 1 has connection to only points 2,3,5  . This means when looking at the A  matrix, there will be a 1  in the first row, at columns 2,3,5  . Similarly, point 2  has connections only to 1,4,6  , which means in the second row there will be a 1  at columns 1,4,6  . Extending the number of points to n = 3  to better see the pattern of A  results in

pict

From the above it is seen that for example point 1  is connected only to 2,4,10  and point 2  is connected to 1, 3,5,11  and so on.

The above shows that each point will have a connection to a point which is numbered n2   higher than the grid point itself.  2
n   is the size of the grid at each surface. Hence, the general A  matrix, for the above example, can now be written as

pict

The recursive structure can be seen. There are n =  3  main repeating blocks on the diagonal, and each one of them in turn has n =  3  repeating blocks on its own diagonal. Here n =  3  , the number of grid points along one dimension.

Now that the A  structure is understood, the A matrix can be generated.

Example 1: Using nx = 2  , ny = 2  , nz =  2  . These are the number of grid points in the x,y,z  directions respectively.



Mathematica

( − 6 1 1  0 1  0  0 0 )
|  1 − 6 1 1 0  1  0 0 |
||  1 1 − 6 1 1  0  1 0 ||
||                      ||
||  0 1  1 − 6 1 1  0 1 ||
|  1 0  1  1 − 6 1 1 0 |
||  0 1  0  1 1 − 6 1 1 ||
(  0 0  1  0 1  1 − 6 1 )
   0 0  0  1 0  1  1 − 6



 


Matlab

 
ans = 
 -6  1  1  0  1  0  0  0 
  1 -6  0  1  0  1  0  0 
  1  0 -6  1  0  0  1  0 
  0  1  1 -6  0  0  0  1 
  1  0  0  0 -6  1  1  0 
  0  1  0  0  1 -6  0  1 
  0  0  1  0  1  0 -6  1 
  0  0  0  1  0  1  1 -6



 

Example 2: Using nx = 2  , ny =  2  , nz =  3  .



Mathematica

(−6 1 1 0 1 0 0 0 0 0 0 0 )
|| 11 −61 −16 11 01 10 01 00 00 00 00 00 ||
||| 0 1 1 −6 1 1 0 1 0 0 0 0 |||
|| 1 0 1 1 −6 1 1 0 1 0 0 0 ||
||| 0 1 0 1 1 − 6 1 1 0 1 0 0 |||
|| 00 00 10 01 10 11 −16 − 161 1 01 10 01 ||
||| 0 0 0 0 1 0 1 1 −6 1 1 0 |||
|| 0 0 0 0 0 1 0 1 1 −6 1 1 ||
( 0 0 0 0 0 0 1 0 1 1 −6 1 )
  0 0 0 0 0 0 0 1 0 1 1 −6



 


Matlab

 
ans = 
 -6  1  1  0  1  0  0  0  0  0  0  0 
  1 -6  0  1  0  1  0  0  0  0  0  0 
  1  0 -6  1  0  0  1  0  0  0  0  0 
  0  1  1 -6  0  0  0  1  0  0  0  0 
  1  0  0  0 -6  1  1  0  1  0  0  0 
  0  1