UP
PDF letter size
PDF legal size

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

September 5, 2017 compiled on — Tuesday September 05, 2017 at 04:15 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.

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

### 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 given zeros , poles and gain 5.

 Mathematica .syntaxhighlighter {font-size: normalsize!important;} Out[30]= TransferFunctionModel[{      {{5*(1 + s)*(2 + s)}},      s*(4 + s)*(6 + s)}, s]

 Matlab .syntaxhighlighter {font-size: normalsize!important;} num/den =     5 s^2 + 15 s + 10    -------------------    s^3 + 10 s^2 + 24 s

 Maple .syntaxhighlighter {font-size: normalsize!important;} .syntaxhighlighter {font-size: small!important;} .syntaxhighlighter {font-size: normalsize!important;}

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

 Mathematica .syntaxhighlighter {font-size: small!important;} .syntaxhighlighter {font-size: normalsize!important;}

 Matlab .syntaxhighlighter {font-size: normalsize!important;} A =     -4   -25      1     0 B =      1      0 C =      5     0 D =      0

 Maple .syntaxhighlighter {font-size: normalsize!important;} .syntaxhighlighter {font-size: normalsize!important;} .syntaxhighlighter {font-size: normalsize!important;} .syntaxhighlighter {font-size: normalsize!important;}

##### problem 2

Problem: Given the continuous time S transfer function defined by

convert to state space and back to transfer function.

 Mathematica .syntaxhighlighter {font-size: small!important;} .syntaxhighlighter {font-size: normalsize!important;}

 Matlab .syntaxhighlighter {font-size: normalsize!important;} A =     -1    -1      1     0  B =      1      0  C =      1     1  D =      0 .syntaxhighlighter {font-size: normalsize!important;} 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 .syntaxhighlighter {font-size: small!important;}

 Matlab .syntaxhighlighter {font-size: normalsize!important;}

 Maple .syntaxhighlighter {font-size: normalsize!important;}

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

Use sampling period of 0.1 seconds.

 Mathematica .syntaxhighlighter {font-size: small!important;} .syntaxhighlighter {font-size: normalsize!important;} .syntaxhighlighter {font-size: normalsize!important;} .syntaxhighlighter {font-size: normalsize!important;} .syntaxhighlighter {font-size: small!important;}

 Matlab .syntaxhighlighter {font-size: normalsize!important;} 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 .syntaxhighlighter {font-size: normalsize!important;}

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

 Mathematica .syntaxhighlighter {font-size: normalsize!important;} .syntaxhighlighter {font-size: normalsize!important;}

 Matlab .syntaxhighlighter {font-size: normalsize!important;} 1   --------------      2   3 s  + 2 s + 1 .syntaxhighlighter {font-size: normalsize!important;} A =    -0.6667   -0.3333     1.0000         0 B =      1      0 C =          0    0.3333 D =      0

 Maple .syntaxhighlighter {font-size: normalsize!important;} .syntaxhighlighter {font-size: normalsize!important;}

#### 1.1.6 Convert from continuous transfer function to discrete time transfer function

Problem: Convert

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

 Mathematica .syntaxhighlighter {font-size: normalsize!important;}

 Matlab .syntaxhighlighter {font-size: normalsize!important;} 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 .syntaxhighlighter {font-size: small!important;} 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

 Mathematica .syntaxhighlighter {font-size: small!important;}

 Matlab .syntaxhighlighter {font-size: normalsize!important;}

 Maple .syntaxhighlighter {font-size: normalsize!important;}

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

and display these on the same plot up to some 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 .syntaxhighlighter {font-size: normalsize!important;} {1 - E^(-t/10) Cos[(3 Sqrt[11] t)/10]  - ( E^(-t/10) Sin[(3 Sqrt[11]t)/10])/                        (3 Sqrt[11])} .syntaxhighlighter {font-size: small!important;} {(10 E^(-t/10) HeavisideTheta[t]   Sin[(3 Sqrt[11] t)/10])/(3 Sqrt[11])} .syntaxhighlighter {font-size: small!important;}

 Matlab .syntaxhighlighter {font-size: normalsize!important;}

 Maple Using Maple DynamicSystems .syntaxhighlighter {font-size: normalsize!important;} Using Laplace transform method: .syntaxhighlighter {font-size: normalsize!important;}

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

when the input is given by

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 .syntaxhighlighter {font-size: small!important;}

 Matlab .syntaxhighlighter {font-size: normalsize!important;}

 Maple .syntaxhighlighter {font-size: normalsize!important;} Using DynamicSystem package .syntaxhighlighter {font-size: normalsize!important;}

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

 Mathematica .syntaxhighlighter {font-size: small!important;} {{{}}} .syntaxhighlighter {font-size: normalsize!important;} {{{-2.-4.58258 I,-2.+4.58258 I}}}

 Matlab .syntaxhighlighter {font-size: normalsize!important;} z =    Empty matrix: 0-by-1  p =   -2.0000 + 4.5826i   -2.0000 - 4.5826i

 Maple .syntaxhighlighter {font-size: small!important;} 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

 Mathematica .syntaxhighlighter {font-size: small!important;}

 Matlab .syntaxhighlighter {font-size: normalsize!important;}

 Maple .syntaxhighlighter {font-size: small!important;} or can plot the the two bode figures on top of each others as follows .syntaxhighlighter {font-size: normalsize!important;}

### 1.7 How to check that state space system is controllable?

A system described by

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

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

And

 Mathematica .syntaxhighlighter {font-size: normalsize!important;} .syntaxhighlighter {font-size: normalsize!important;} True .syntaxhighlighter {font-size: normalsize!important;} 4

 Matlab .syntaxhighlighter {font-size: normalsize!important;} m =      0     1     0     2      1     0     2     0      0    -2     0   -10     -2     0   -10     0 .syntaxhighlighter {font-size: normalsize!important;} 4

 Maple .syntaxhighlighter {font-size: normalsize!important;} .syntaxhighlighter {font-size: normalsize!important;} true .syntaxhighlighter {font-size: small!important;} true .syntaxhighlighter {font-size: normalsize!important;} 4

### 1.8 Obtain partial-fraction expansion

Problem: Given the continuous time S transfer function defined by

obtain the partial-fractions decomposition.

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

 Mathematica .syntaxhighlighter {font-size: normalsize!important;} 2 + s +3/(1+s) -4/(2+s) -6/(3+s)

 Matlab .syntaxhighlighter {font-size: normalsize!important;} r =    -6.0000    -4.0000     3.0000  p =    -3.0000    -2.0000    -1.0000  k =      1     2

 Maple .syntaxhighlighter {font-size: small!important;} .syntaxhighlighter {font-size: normalsize!important;}

### 1.9 Obtain Laplace transform for a piecewise functions

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

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 .syntaxhighlighter {font-size: small!important;} Out[]= (1 - E^((-s)*T))/s^2

 Matlab .syntaxhighlighter {font-size: normalsize!important;} 1 - exp(-T s)   -------------         2        s

 Maple With Maple, had to use Heaviside else Laplace will not obtain the transform of a piecewise function. .syntaxhighlighter {font-size: normalsize!important;}

### 1.10 Obtain Inverse Laplace transform of a transfer function

Problem: Obtain the inverse Laplace transform for the function

Mathematica

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

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

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

Mathematica

Matlab

Maple

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

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

Problem: Given the transfer function

Display the output and input on the same plot showing how the steady state error changes as the un damped natural frequency 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 seconds and and change from to .

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

find which is the inverse Ztransform.

 Mathematica .syntaxhighlighter {font-size: small!important;}

 Matlab .syntaxhighlighter {font-size: small!important;}

#### 1.13.2 example 2

Problem: Given

find

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

 Mathematica .syntaxhighlighter {font-size: normalsize!important;} Inverse Z is 5 n .syntaxhighlighter {font-size: normalsize!important;}

 Matlab .syntaxhighlighter {font-size: normalsize!important;}

### 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 defined as  for , find its Z transform.

 Mathematica .syntaxhighlighter {font-size: normalsize!important;} Out[] = z/(-1+z)

 Matlab .syntaxhighlighter {font-size: normalsize!important;} 1   ----- + 1/2   z - 1

#### 1.14.2 example 2

Find the Z transform for

 Mathematica .syntaxhighlighter {font-size: small!important;} z (3/(-1+3 z)+10000/(729 (-9+10 z)))

 Matlab .syntaxhighlighter {font-size: normalsize!important;} 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

Use sampling frequency Hz and show the result for up to seconds. Use as input the signal .

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

Mathematica

Matlab

plantD =

0.6976 z - 0.6976
------------------------
z^2 - 0.5032 z + 0.04979

Sample time: 1 seconds
Discrete-time transfer function.

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

Problem: Given

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

 Mathematica .syntaxhighlighter {font-size: normalsize!important;} .syntaxhighlighter {font-size: small!important;} The system wrapper can be removed in order to obtain the rational polynomial expression as follows .syntaxhighlighter {font-size: normalsize!important;}

 Matlab .syntaxhighlighter {font-size: normalsize!important;} Transfer function:        s --------------- s^2 + 10 s + 20

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

 Mathematica .syntaxhighlighter {font-size: normalsize!important;} .syntaxhighlighter {font-size: normalsize!important;}

 Matlab .syntaxhighlighter {font-size: normalsize!important;} 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 in the Riccati equation

given

 Mathematica .syntaxhighlighter {font-size: normalsize!important;}

 Matlab .syntaxhighlighter {font-size: normalsize!important;} 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

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

The Riccati equation is given by

Let .

 Mathematica .syntaxhighlighter {font-size: small!important;} .syntaxhighlighter {font-size: normalsize!important;} .syntaxhighlighter {font-size: normalsize!important;}

 Matlab .syntaxhighlighter {font-size: normalsize!important;} dsys =     0.4261 z + 0.3608   ----------------------   z^2 - 1.607 z + 0.6065  Sample time: 1 seconds Discrete-time transfer function. .syntaxhighlighter {font-size: normalsize!important;} 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 .syntaxhighlighter {font-size: normalsize!important;} 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 and using sampling period of find continuous time approximation using zero order hold and show the impulse response of the system and compare both responses.

Mathematica

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

Find the impulse response of the continuous time system

Plot the impulse response of the discrete system

Plot the impulse response of the continuous system

Plot both responses on the same plot

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

Matlab

### 1.21 Find the system type given an open loop transfer function

Problem: Find the system type for the following transfer functions

To find the system type, the transfer function is put in the form , then the system type is the exponent . Hence it can be seen that the first system above has type one since the denominator can be written as and the second system has type 2 since the denominator can be written as and the third system has type 5. The following computation determines the type

 Mathematica .syntaxhighlighter {font-size: small!important;} Out[171]= 1 .syntaxhighlighter {font-size: small!important;} Out[173]= 2 .syntaxhighlighter {font-size: small!important;} Out[175]= 5

 Matlab .syntaxhighlighter {font-size: small!important;} ans =      1 .syntaxhighlighter {font-size: small!important;} ans =      2 .syntaxhighlighter {font-size: small!important;} ans =      5

### 1.22 Find the eigenvalues and eigenvectors of a matrix

Problem, given the matrix

Find its eigenvalues and eigenvectors.

 Mathematica .syntaxhighlighter {font-size: small!important;} .syntaxhighlighter {font-size: normalsize!important;} .syntaxhighlighter {font-size: normalsize!important;}

 Matlab Matlab generated eigenvectors are such that the sum of the squares of the eigenvector elements add to one. .syntaxhighlighter {font-size: normalsize!important;} 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

 Mathematica .syntaxhighlighter {font-size: normalsize!important;}

 Matlab Note: Matlab generated characteristic polynomial coefficients are negative to what Mathematica generated. .syntaxhighlighter {font-size: normalsize!important;} 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

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 .syntaxhighlighter {font-size: normalsize!important;} .syntaxhighlighter {font-size: normalsize!important;} Another way is as follows .syntaxhighlighter {font-size: normalsize!important;}

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 .syntaxhighlighter {font-size: normalsize!important;} 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

#### 1.25.1 Checking stability using transfer function poles

 Mathematica .syntaxhighlighter {font-size: small!important;} {{{-2-I Sqrt[21],-2+I Sqrt[21]}}} .syntaxhighlighter {font-size: small!important;} Out[42]= {{{-2,-2}}} .syntaxhighlighter {font-size: normalsize!important;} Out[44]= {}

 Matlab .syntaxhighlighter {font-size: normalsize!important;} >> p =   -2.0000 + 4.5826i   -2.0000 - 4.5826i .syntaxhighlighter {font-size: normalsize!important;} ans =    Empty matrix: 0-by-1

#### 1.25.2 Checking stability using state space A matrix

 Mathematica .syntaxhighlighter {font-size: normalsize!important;} Out[49]= {{0,1},{-25,-4}} .syntaxhighlighter {font-size: normalsize!important;} Out[50]= {-2+I Sqrt[21],-2-I Sqrt[21]} .syntaxhighlighter {font-size: normalsize!important;} Out[51]= {-2,-2} .syntaxhighlighter {font-size: normalsize!important;} Out[52]= {}

 Matlab .syntaxhighlighter {font-size: normalsize!important;} A =    -4.0000   -6.2500     4.0000         0 .syntaxhighlighter {font-size: normalsize!important;} e =   -2.0000 + 4.5826i   -2.0000 - 4.5826i .syntaxhighlighter {font-size: normalsize!important;} 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

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 when calling these functions, since the Lyapunov equation is defined as and this is not how the software above defines them. By simply transposing the matrix when calling them, then the result will be correct.

 Mathematica .syntaxhighlighter {font-size: normalsize!important;} .syntaxhighlighter {font-size: normalsize!important;} .syntaxhighlighter {font-size: normalsize!important;}

 Matlab .syntaxhighlighter {font-size: normalsize!important;} p =   2.3   2.1  0.5   2.1   4.6  1.3   0.5   1.3  0.6 .syntaxhighlighter {font-size: normalsize!important;} e =      0.20238        1.1149        6.1827

 Maple .syntaxhighlighter {font-size: small!important;}

### 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 , generate the closed loop transfer function, and that poles of the closed loop transfer function are inside the unit circle

System block diagram.

Mathematica

Now generate unit step response

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.

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 .syntaxhighlighter {font-size: small!important;} .syntaxhighlighter {font-size: small!important;}

 Matlab .syntaxhighlighter {font-size: small!important;}

### 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 due some existing initial conditions in the states. There is no input forces.

 Mathematica .syntaxhighlighter {font-size: small!important;} .syntaxhighlighter {font-size: small!important;}

 Matlab .syntaxhighlighter {font-size: small!important;}

### 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 .syntaxhighlighter {font-size: small!important;} .syntaxhighlighter {font-size: normalsize!important;}

 Matlab .syntaxhighlighter {font-size: small!important;}

### 1.31 Draw the root locus from the open loop transfer function

Problem: Given , the open loop transfer function, draw the root locus. Let

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

 Mathematica .syntaxhighlighter {font-size: small!important;}

 Matlab .syntaxhighlighter {font-size: normalsize!important;}

### 1.32 Find where is a matrix

Mathematica

Now verify the result by solving for 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

Out[15]= {{lambda->-2},{lambda->-1}}

Out[16]= -2
Out[17]= -1

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

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

 Mathematica .syntaxhighlighter {font-size: small!important;} .syntaxhighlighter {font-size: small!important;}

 Matlab .syntaxhighlighter {font-size: small!important;}

### 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.

Mathematica

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

Matlab

### 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 , damping coefficient and let the stiffness coefficient be .

Using propertional controller where . First connect the system and then show for 5 seconds when the reference is a unit step function.

Mathematica

Matlab

Another way to do the above is

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

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

Where and are the Laplace transforms of the output and input respectively.

Hence the differential equation, assuming zero initial conditions becomes

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

For a step input, , we obtain

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

Mathematica

Matlab

### 1.37 Plot the dynamic response factor of a system as a function of for different damping ratios

Problem: Plot the standard curves showing how the dynamic response changes as 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 is the natural frequency of the system.

 Mathematica .syntaxhighlighter {font-size: small!important;} .syntaxhighlighter {font-size: small!important;}

### 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 connected to a PID controller with . Use negative closed loopback.

 Mathematica .syntaxhighlighter {font-size: small!important;}

 Matlab .syntaxhighlighter {font-size: small!important;}

### 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 , then we know that the closed loop transfer function is . But we call Nyquist with .

Here are two examples.

#### 1.39.1 Example 1

Given generate Nyquist plot.

 Mathematica .syntaxhighlighter {font-size: normalsize!important;}

 Matlab .syntaxhighlighter {font-size: normalsize!important;}

#### 1.39.2 Example 2

Given generate Nyquist plot.

 Mathematica .syntaxhighlighter {font-size: small!important;}

 Matlab .syntaxhighlighter {font-size: small!important;} 2.5 s - 5   ------------------------   0.025 s^3 + 0.15 s^2 - s  Continuous-time transfer function. .syntaxhighlighter {font-size: normalsize!important;}

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

 .syntaxhighlighter {font-size: normalsize!important;}

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

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 of 3 rows, and want to find the location where where is the row number and is the column number. Given this matrix

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 .syntaxhighlighter {font-size: normalsize!important;} Out[7]= {14,32,47}

 Matlab .syntaxhighlighter {font-size: normalsize!important;} 14     32     50

compile and run

gnatbind -x 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 .syntaxhighlighter {font-size: small!important;}

 Python .syntaxhighlighter {font-size: normalsize!important;} 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 .syntaxhighlighter {font-size: normalsize!important;} Out[11]= {1,2,99,3,4}

 Matlab .syntaxhighlighter {font-size: normalsize!important;} A =      1     2    99     3     4

 Fortran .syntaxhighlighter {font-size: small!important;} >gfortran -std=f2008 t2.f90 >./a.out  1.0000000 2.0000000 99.000000           3.0000000 4.0000000

 Maple .syntaxhighlighter {font-size: small!important;} Using <> notation .syntaxhighlighter {font-size: small!important;} v :=[ 1 2 99 3 4]

 Python Python uses zero index. .syntaxhighlighter {font-size: normalsize!important;} 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 .syntaxhighlighter {font-size: normalsize!important;} {{1,2,3},   {90,91,92},   {4,5,6},   {7,8,9}}

 Matlab .syntaxhighlighter {font-size: normalsize!important;} 1     2     3     90    91    92      4     5     6      7     8     9

 Maple Using <<>> notation .syntaxhighlighter {font-size: normalsize!important;} Using Matrix/Vector .syntaxhighlighter {font-size: normalsize!important;} [ 1  2   3   4  5   6   90 91  92   7  8   9]

 Python .syntaxhighlighter {font-size: small!important;} array([[ 1,  2,  3],        [90, 91, 92],        [ 4,  5,  6],        [ 7,  8,  9]])

 Fortran .syntaxhighlighter {font-size: normalsize!important;} 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 .syntaxhighlighter {font-size: normalsize!important;} {{1,90,2,3},   {4,91,5,6},   {7,92,8,9}}

 Matlab .syntaxhighlighter {font-size: normalsize!important;} 1    90     2     3      4    91     5     6      7    92     8     9

 Fortran .syntaxhighlighter {font-size: small!important;} >gfortran t4.f90 >./a.out  1          90           2           3  4          91           5           6  7          92           8           9

 Maple .syntaxhighlighter {font-size: small!important;} Using Matrix/Vector .syntaxhighlighter {font-size: small!important;} [ 1    90     2     3   4    91     5     6   7    92     8     9]

 Python .syntaxhighlighter {font-size: normalsize!important;} 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 and and and generate the matrix

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 .syntaxhighlighter {font-size: normalsize!important;}

 Matlab .syntaxhighlighter {font-size: normalsize!important;} m =      1     4      2     5      3     6      7    10      8    11      9    12

 Maple .syntaxhighlighter {font-size: normalsize!important;}

 Python .syntaxhighlighter {font-size: normalsize!important;} Another way .syntaxhighlighter {font-size: normalsize!important;} Out[211]: array([[ 1,  4],        [ 2,  5],        [ 3,  6],        [ 7, 10],        [ 8, 11],        [ 9, 12]])

 Fortran .syntaxhighlighter {font-size: small!important;} Using the RESHAPE command .syntaxhighlighter {font-size: small!important;} >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 and and and and

generate the matrix 6 by 3 matrix

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 .syntaxhighlighter {font-size: small!important;} {{0.100843,0.356115,0.700317,0.657852},   {0.238019,0.59598,0.523526,0.576362},   {0.339828,0.32922,0.0632487,0.815892}} .syntaxhighlighter {font-size: small!important;} {{-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 .syntaxhighlighter {font-size: small!important;} 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 .syntaxhighlighter {font-size: small!important;} 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 .syntaxhighlighter {font-size: small!important;} [[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

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 .syntaxhighlighter {font-size: normalsize!important;} {{0,0,0,0},      {0,0,0,0},      {0,0,0,0}}

 Matlab .syntaxhighlighter {font-size: normalsize!important;} A =      0     0     0     0      0     0     0     0      0     0     0     0

 Maple .syntaxhighlighter {font-size: normalsize!important;}

 Fortran .syntaxhighlighter {font-size: small!important;}  tmp>gfortran -std=f2008 f.f90 tmp>./a.out 0.0000000000000000        0.0000000000000000        0.0000000000000000        0.0000000000000000 0.0000000000000000        0.0000000000000000        0.0000000000000000        0.0000000000000000 0.0000000000000000        0.0000000000000000        0.0000000000000000        0.0000000000000000

### 2.8 Rotate a matrix by 90 degrees

 Mathematica .syntaxhighlighter {font-size: normalsize!important;} {{3,6,9},      {2,5,8},      {1,4,7}}

 Matlab .syntaxhighlighter {font-size: normalsize!important;} 3     6     9      2     5     8      1     4     7

 Maple .syntaxhighlighter {font-size: normalsize!important;} [[3,2,1],  [6,5,4],  [9,8,7]] .syntaxhighlighter {font-size: normalsize!important;} [[3,6,9],     [2,5,8],     [1,4,7]]

 Fortran Using additional copy for the matrix .syntaxhighlighter {font-size: small!important;}  mp>gfortran -std=f2008 f.f90 tmp>./a.out            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 on the diagonal.

 Mathematica .syntaxhighlighter {font-size: normalsize!important;} {{2,0,0,0},       {0,4,0,0},       {0,0,6,0},       {0,0,0,8}}

 Matlab .syntaxhighlighter {font-size: normalsize!important;} 2     0     0     0      0     4     0     0      0     0     6     0      0     0     0     8

 Maple .syntaxhighlighter {font-size: small!important;} [[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 .syntaxhighlighter {font-size: normalsize!important;} Out[45]= 15

 Matlab .syntaxhighlighter {font-size: normalsize!important;} ans =     15

 Maple .syntaxhighlighter {font-size: normalsize!important;} Another ways .syntaxhighlighter {font-size: normalsize!important;} 15

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

 Mathematica .syntaxhighlighter {font-size: normalsize!important;} Out[49]= 45

 Matlab .syntaxhighlighter {font-size: normalsize!important;} ans = 45

 Maple .syntaxhighlighter {font-size: normalsize!important;} 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 .syntaxhighlighter {font-size: footnotesize!important;} Out[59]= False   Out[60]= True   Out[61]= False

 Maple .syntaxhighlighter {font-size: footnotesize!important;} 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 in this example.

 Mathematica .syntaxhighlighter {font-size: normalsize!important;} {{1,2},{1,3},{2,1},{3,1}}

 Matlab .syntaxhighlighter {font-size: normalsize!important;} I =      2      3      1      1 J =      1      1      2      3

 Maple .syntaxhighlighter {font-size: footnotesize!important;} [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 by 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 .syntaxhighlighter {font-size: normalsize!important;} {{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 .syntaxhighlighter {font-size: normalsize!important;} 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 .syntaxhighlighter {font-size: normalsize!important;} {{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 .syntaxhighlighter {font-size: normalsize!important;} 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 .syntaxhighlighter {font-size: normalsize!important;} [[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 .syntaxhighlighter {font-size: small!important;} Out[142]= {{2,2},{3,3}}

 Matlab .syntaxhighlighter {font-size: normalsize!important;} r =      2      3 c =      2      3

 Maple This below finds position of first max. .syntaxhighlighter {font-size: normalsize!important;} 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 .syntaxhighlighter {font-size: footnotesize!important;} [[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 .syntaxhighlighter {font-size: normalsize!important;} Out[29]= {{2, 1},           {4, 3},           {6, 5}}

 Matlab .syntaxhighlighter {font-size: normalsize!important;} 2     1      4     3      6     5

 Maple .syntaxhighlighter {font-size: normalsize!important;} [[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 .syntaxhighlighter {font-size: normalsize!important;} Out[146]= {{8,5, 1},            {8,10,8},            {6,0, 8}} .syntaxhighlighter {font-size: normalsize!important;} {{9, 0,1},  {10,2,7},  {8, 0,8}} .syntaxhighlighter {font-size: normalsize!important;} {{8,5, 1, 9,0,1},  {8,10,8,10,2,7},  {6,0, 8, 8,0,8}} .syntaxhighlighter {font-size: normalsize!important;} {{8, 5 , 1},  {8, 10, 8},  {6, 0 , 8},  {9, 0 , 1},  {10,2 , 7},  {8, 0 , 8}}

 Matlab .syntaxhighlighter {font-size: normalsize!important;} 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 .syntaxhighlighter {font-size: normalsize!important;} 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 .syntaxhighlighter {font-size: normalsize!important;}

### 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 .syntaxhighlighter {font-size: normalsize!important;} {{1, 2, 4, 2},   {2, 3, 9, 2},   {4, 9, 5, 3},   {2, 2, 3, 4}  }

 Matlab .syntaxhighlighter {font-size: normalsize!important;} ans =      1     2     4     2      2     3     9     2      4     9     5     3      2     2     3     4

 Maple .syntaxhighlighter {font-size: normalsize!important;} [[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 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 and which will be and in this example.

 Mathematica .syntaxhighlighter {font-size: normalsize!important;} {1,9} Another method (same really as above, but using Part explicit) .syntaxhighlighter {font-size: normalsize!important;} {1,9}

 Matlab .syntaxhighlighter {font-size: normalsize!important;} ans =      1     9

 Maple .syntaxhighlighter {font-size: normalsize!important;} [1, 9]

### 2.20 Convert by matrix to a row of length

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 .syntaxhighlighter {font-size: normalsize!important;} {1,2,3,4,5,6,7,8,9}

 Matlab .syntaxhighlighter {font-size: normalsize!important;} 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. .syntaxhighlighter {font-size: small!important;} Notice the result is a row matrix and not a vector. To get a vector .syntaxhighlighter {font-size: normalsize!important;} 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 in the second column and in the last column. Hence the result will be the first and third rows only

1     9     0    10
3     9     2    10
 Mathematica .syntaxhighlighter {font-size: normalsize!important;} {{1},{3}} .syntaxhighlighter {font-size: normalsize!important;} {{1,9,0,10},   {3,9,2,10}}

 Matlab .syntaxhighlighter {font-size: normalsize!important;} ans =      1     9     0    10      3     9     2    10

 Maple .syntaxhighlighter {font-size: small!important;} [[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 .syntaxhighlighter {font-size: normalsize!important;} {6, 7, 2} another way is to find the index using Position and then use Extract .syntaxhighlighter {font-size: normalsize!important;} {6, 7, 2} another way is to use Cases[]. This is the shortest way .syntaxhighlighter {font-size: normalsize!important;} {6, 7, 2}

 Matlab .syntaxhighlighter {font-size: normalsize!important;} 6      7      2

 Maple .syntaxhighlighter {font-size: small!important;} [[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 .syntaxhighlighter {font-size: small!important;} {{"foo", 126}, {"faa", 177}}

 Matlab .syntaxhighlighter {font-size: footnotesize!important;} ans =     ’foo’    ’faa’     [126]    [177] But notice that in Matlab, the answer is a cellarray. To access the numbers above .syntaxhighlighter {font-size: normalsize!important;} 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.

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[] .syntaxhighlighter {font-size: normalsize!important;} {{0, 2, 1, 0},  {4, 3, 3, 2},  {3, 4, 3, 3},  {5, 4, 2, 0} } method 2: (due to Mr Wizard at stackoverflow) .syntaxhighlighter {font-size: normalsize!important;} {{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. .syntaxhighlighter {font-size: normalsize!important;} Out[39]= {{0,2,1,0},           {4,3,3,2},           {3,4,3,3},           {5,4,2,0}}

 Matlab .syntaxhighlighter {font-size: normalsize!important;} 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 .syntaxhighlighter {font-size: normalsize!important;} List["12","537","4"]

 Matlab .syntaxhighlighter {font-size: normalsize!important;} ans =     ’1  2’     ’5  3  7’     ’4’ answer below is due to Bruno Luong at Matlab newsgroup .syntaxhighlighter {font-size: normalsize!important;} ’12’    ’537’    ’4’

### 2.26 Obtain elements that are common to two vectors

Given vector or list , find the common elements.

 Mathematica .syntaxhighlighter {font-size: normalsize!important;} Out[412]= {7,50}

 Matlab .syntaxhighlighter {font-size: normalsize!important;} 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 .syntaxhighlighter {font-size: normalsize!important;} {{2, 1, 2},  {4, 2, 5},  {10,7, 9}}

 Matlab .syntaxhighlighter {font-size: normalsize!important;} 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 .syntaxhighlighter {font-size: normalsize!important;} {{2, 4, 5}, {2, 7, 9}, {1, 2, 10}}

 Matlab .syntaxhighlighter {font-size: normalsize!important;} 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 .syntaxhighlighter {font-size: normalsize!important;} {{2,  7, 9}, {4,  2, 5}, {10, 1, 2}}

 Matlab .syntaxhighlighter {font-size: normalsize!important;} 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 .syntaxhighlighter {font-size: normalsize!important;} {{10, 1, 2}, {4,  2, 5}, {2,  7, 9}}

 Matlab .syntaxhighlighter {font-size: normalsize!important;} 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 below, replace the first non-zero element in each row by , then

will become

 Mathematica .syntaxhighlighter {font-size: small!important;} Solution due to Bob Hanlon (from Mathematica newsgroup) .syntaxhighlighter {font-size: normalsize!important;} Solution by Fred Simons (from Mathematica newsgroup) .syntaxhighlighter {font-size: normalsize!important;} Solution due to Adriano Pascoletti (from Mathematica newsgroup) .syntaxhighlighter {font-size: small!important;} Solution due to Oliver Ruebenkoenig (from Mathematica newsgroup) .syntaxhighlighter {font-size: normalsize!important;} Solution due to Szabolcs Horvát (from Mathematica newsgroup) .syntaxhighlighter {font-size: small!important;} {{-1,75,0},{-1,0,100},{0,-1,100}, {-1,100,0},{0,-1,100},{0,-1,100}}

 Matlab .syntaxhighlighter {font-size: normalsize!important;} This solution due to Bruno Luong (from matlab newsgroup) .syntaxhighlighter {font-size: normalsize!important;} This solution due to Jos from matlab newsgroup .syntaxhighlighter {font-size: normalsize!important;} 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 .syntaxhighlighter {font-size: normalsize!important;} {{a e, a f, a g}, {b e, b f, b g}, {c e, c f, c g}} Outer sum .syntaxhighlighter {font-size: normalsize!important;} {{a+e, a+f, a+g}, {b+e, b+f, b+g}, {c+e, c+f, c+g}} using numerical vectors. Outer product .syntaxhighlighter {font-size: normalsize!important;} {{4,  5,  6}, {8,  10, 12}, {12, 15, 18}} Outer sum .syntaxhighlighter {font-size: normalsize!important;} {{5, 6, 7},    {6, 7, 8},    {7, 8, 9}}

 Matlab Outer product .syntaxhighlighter {font-size: normalsize!important;} ans =      4     5     6      8    10    12     12    15    18 Outer sum .syntaxhighlighter {font-size: normalsize!important;} ans =      5     6     7      6     7     8      7     8     9

 Maple Due to Carl Love from the Maple newsgroup .syntaxhighlighter {font-size: small!important;} [a*d,a*e,a*f,b*d,   b*e, b*f, c*d, c*e, c*f] .syntaxhighlighter {font-size: normalsize!important;} [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.

 Mathematica .syntaxhighlighter {font-size: normalsize!important;} 3,4 .syntaxhighlighter {font-size: footnotesize!important;} Rank (or dimension of the range space)=3 .syntaxhighlighter {font-size: footnotesize!important;} Dimension of the Null Space=1 .syntaxhighlighter {font-size: footnotesize!important;} Basis for Null Space={{3,-4,2,0}}

 Matlab .syntaxhighlighter {font-size: footnotesize!important;} 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 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 .syntaxhighlighter {font-size: footnotesize!important;} {{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}} .syntaxhighlighter {font-size: small!important;} {{1.,2.,3.}, {4.,5.,6.}}

 Matlab .syntaxhighlighter {font-size: normalsize!important;} 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 .syntaxhighlighter {font-size: normalsize!important;} ans =     1.0000    2.0000    3.0000     4.0000    5.0000    6.0000

 Maple .syntaxhighlighter {font-size: normalsize!important;} [1    2    3 ] A := [            ]      [4    5    6.] .syntaxhighlighter {font-size: small!important;} [0.386317703118612    -0.922365780077058]  [                                       ]  [0.922365780077058    0.386317703118612 ] .syntaxhighlighter {font-size: normalsize!important;} [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 ] .syntaxhighlighter {font-size: footnotesize!important;} [9.50803200069572        0            0] s2 := [                                      ]       [       0         0.772869635673485    0] .syntaxhighlighter {font-size: small!important;} [1.    2.    3.] [              ] [4.    5.    6.]

### 2.35 Solve

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 .syntaxhighlighter {font-size: normalsize!important;} {0,0,1/3}

 Matlab .syntaxhighlighter {font-size: normalsize!important;} 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

the positions returned will be and the corresponding values are .

 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. .syntaxhighlighter {font-size: normalsize!important;} {{1,3},{2,1},{2,3},{3,1},{3,2}} .syntaxhighlighter {font-size: normalsize!important;} {1,10,2,3,4} Or standard list operations can be used .syntaxhighlighter {font-size: small!important;} {1,10,2,3,4} .syntaxhighlighter {font-size: normalsize!important;} {{1,3},{2,1},{2,3},{3,1},{3,2}}