Skip to main content

Finite Difference Methods and MATLAB

  • Chapter
  • First Online:
Book cover System Dynamics

Abstract

Finite difference approximations are the foundation of computer-based numerical solutions of differential equations. Numerical solutions, also known as numerical methods, are essential to solve non-linear differential equations. The state-space representation of dynamic systems requires numerical solution. The Euler method is the simplest finite difference method and is used to introduce the concepts. The more accurate Runge–Kutta algorithm is also more involved. Fortunately, the use of the Runge–Kutta method is straightforward. The Appendix to the chapter is a brief introduction to computer programming and programming in MATLAB for those who need it.

This is a preview of subscription content, log in via an institution to check access.

Access this chapter

Chapter
USD 29.95
Price excludes VAT (USA)
  • Available as PDF
  • Read on any device
  • Instant download
  • Own it forever
eBook
USD 69.99
Price excludes VAT (USA)
  • Available as EPUB and PDF
  • Read on any device
  • Instant download
  • Own it forever
Softcover Book
USD 89.99
Price excludes VAT (USA)
  • Compact, lightweight edition
  • Dispatched in 3 to 5 business days
  • Free shipping worldwide - see info
Hardcover Book
USD 119.99
Price excludes VAT (USA)
  • Durable hardcover edition
  • Dispatched in 3 to 5 business days
  • Free shipping worldwide - see info

Tax calculation will be finalised at checkout

Purchases are for personal use only

Institutional subscriptions

References and Suggested Reading

  • Hamming RW (1973) Numerical Methods for Scientists and engineers, 2nd edn. Dover, New York

    Google Scholar 

  • Press WH, Teukolsky SA, Vetterling WT, Flannery BP (2007) Numerical recipes, 3rd edn. Cambridge University, Cambridge

    Google Scholar 

Download references

Author information

Authors and Affiliations

Authors

Corresponding author

Correspondence to Karl A. Seeler .

Appendices

Summary

Finite difference methods are necessary to solve non-linear system equations. State equations are solved using finite difference methods in all cases. The state-space representation is particularly convenient for non-linear dynamic systems. The Euler method was the first method of finite differences and remains the simplest. The Runge-Kutta method is the most widely used because of its accuracy and numerical stability.

Problems

Problem 8.1 The rotational system shown schematically in Fig. P8.1 comprises an angular velocity input driving a fluid coupling attached to a compliant shaft modeled as a spring. The compliant shaft drives a flywheel with mass moment of inertia J. Two sets of parameters, Case I and Case II, are tabulated.

Fig. P8.1
figure 16

A rotational mechanical system

Table P8.1 Parameter values
  • 8.1.a Derive the state equations for this system.

  • 8.1.b Derive the output equations for:

    • i The angular velocity of the inertia J.

    • ii The torque acting through the compliant shaft spring K.

    • iii The angular velocity difference across the compliant shaft spring K.

    • iv The angular velocity difference across the fluid coupling b.

  • 8.1.c Express the state and output equations in matrix form.

  • 8.1.d For Cases I and II, calculate the system’s eigenvalues. If the system is underdamped, determine the ideal, undamped natural frequency ω n , the damped natural frequency ω d , and the damping ratio ζ.

  • 8.1.e The system is de-energized when it is acted on by a step input of 10 rad/s. Write a MATLAB program for the Euler method to solve the state equations, and, using the solution of the state equations, solve the output equations for Cases I and II. Plot the responses of the output variables.

  • 8.1.f Repeat part e using the Runge–Kutta algorithm.

  • 8.1.g Plot the Euler method and Runge–Kutta algorithm results for the angular velocity of flywheel on the same plot. How does the difference between the results of the two methods vary over the solution?

Problem 8. 2 A mass M supported on frictionless roller is shown in Fig. P8.2a. A dashpot with damping b and a spring with spring constant K are connected between the mass and ground. The mass is acted upon by an applied force F(t).

The system has a linear and a non-linear configuration. The linear configuration has linear dampers, which are described by the equation F b  = bv 1g. The non-linear configuration has non-linear dampers designed so that they exert a damping force when the damper is in compression but not when the damper is in extension, as shown in Fig. P8.2b.

Fig. P8.2
figure 17

a Second-order translational mechanical system, b Nonlinear damper, which exerts a damping force only in compression

Table P8.1 Parameter values
  • 8.2.a Derive the state equations for this system.

  • 8.2.b Derive the output equations for:

    • i The velocity of the mass M.

    • ii The force acting through spring K.

    • iii The angular velocity difference across spring K.

  • 8.2.c Express the state and output equations in matrix form.

  • 8.2.d For the linear Cases I and II, calculate the system’s eigenvalues. If the system is underdamped, determine the ideal, undamped natural frequency ω n , the damped natural frequency ω d , and the damping ratio ζ.

  • 8.2.e Write a MATLAB program to solve the linear state equations using the Runge–Kutta algorithm for a step input of 10 N. Assume that the system was de-energized at time t = 0. Include the code to solve the output equations and plot their responses. Run your code using the parameter values for Cases I and II.

  • 8.2.f Save your MATLAB script to a different file name and edit the script to include the non-linear behavior of the dashpot. Run your program for the same input and parameter values as part e.

Problem 8.3 The fluid system shown schematically in Fig. 8.3a consists of a fluid power unit, modeled as a pressure source, two fluid resistances R 1 = 100 MPa sec/m3 and R 2 = 200 MPa sec/m3, a long run of piping, modeled as a fluid inertance, I = 40 × 107 kg/m4 and a fluid accumulator (capacitance), C = 6 × 10−8 m3/Pa. The system will be modeled twice, a linear and a non-linear model. In the linear model, the fluid resistance R 1 has a constant resistance and allows flow in both directions. In the non-linear model, the fluid resistance R 1 is a check valve which only allows flow in the direction shown. The fluid resistance in the forward direction is the same as the linear case.

Fig. P8.3a
figure 18

Fluid circuit schematic

  • 8.3.a Derive the state equations for this system.

  • 8.3.b Derive the output equations for:

    • i The volume flow rate from the pressure source.

    • ii The pressure in the fluid accumulator.

    • iii The volume flow rate through the fluid inertance.

    • iv The pressure difference across the fluid inertance.

and check their units.

  • 8.3.c Express the state and output equations in matrix form.

  • 8.3.d Calculate the system’s eigenvalues configured with the linear fluid resistance R 1. If the system is underdamped, determine the ideal, undamped natural frequency ω n , the damped natural frequency ω d , and the damping ratio ζ.

The system was de-energized before the pressure pulse plotted in Fig. P8.3b was applied to the system.

8.4.e Write a MATLAB program to solve the linear state equations using the Runge–Kutta algorithm for the pressure input shown in Fig. P8.3b. Assume that the system was de-energized at time t = 0. Include the code to solve the output equations and plot their responses.

Fig. P8.3b
figure 19

Input pressure pulse

  • 8.3.f Save your MATLAB script of part e under a different file name and edit it to solve the non-linear state equations using the Runge–Kutta algorithm for the pressure input shown in Fig. P8.3b.

  • 8.3.g Compare the pressure across the fluid inertance in the linear and non-linear cases and calculate the maximum change in pressure due to the check valve.

Problem 8.4 The electric circuit shown in the schematic, Fig. 8.4a, consists of a voltage source, two resistors, \( {R_{\,1}} = 1\,\,\Omega\) and \( {R_{\,2}} = 0.2\,\Omega , \) a capacitor, C = 20 × 10−6 F, an inductor, L = 1 × 10-6H, and a diode D.

Diodes conduct current only in the direction that the triangle of their symbol points Fig. 8.4b. This is a diode’s “forward” direction. Diodes have a threshold voltage, which varies with the material and design of the diode. A typical silicon diode has threshold voltage of 0.63 VDC before it conducts in the forward direction, Fig. 8.4c. An actual diode’s voltage-current plot is similar to Fig. 8.4c. The small increase in resistance to the forward conduction with increased current is usually neglected and the diode modeled as having the threshold voltage drop but no additional resistance.

Fig. P8.4a
figure 20

Schematic of a RLC circuit with a diode D

Fig. P8.4b
figure 21

Diode schematic symbol showing forward direction (direction of current flow). c Diode voltage-current plot

The system will be modeled in two configurations, a linear configuration without the diode, and a non-linear configuration with the diode.

  • 8.4.a Derive the state equations for the linear configuration and check their units.

  • 8.4.b Derive output equations for the following variables of the linear system.

    • i The voltage across capacitor C.

    • ii The current flowing through inductor L.

    • iii The voltage across inductor L.

    • iv The current through resistor R 1 .

    • v The current through resistor R 2 .

  • 8.4.c Write the state equations and output equations in vector-matrix form.

  • 8.4.d Calculate the system’s eigenvalues If the system is underdamped, determine the ideal, undamped natural frequency ω n , the damped natural frequency ω d, and the damping ratio ζ.

The system is initially de-energized before the voltage pulse shown in Fig. P8.4d was applied.

  • 8.4.e Write a MATLAB program to solve the linear state equations using the Runge–Kutta algorithm for the voltage pulse input shown in Fig. P8.4d. Assume that the system was de-energized at time t = 0. Include the code to solve the output equations and plot their responses.

  • 8.4.f Save your MATLAB script of part e under a different file name and edit the script to solve the state equations for the non-linear configuration, which includes the diode, for the voltage input shown in Fig. P8.4d.

  • 8.4.g Compare the voltage across the inductance in the linear and non-linear systems and calculate the maximum change in voltage due to the diode.

Fig. P8.4d
figure 22

Input voltage

Problem 8.5 Two rotational mechanical systems are shown schematically in Figs. P8.5a and P8.5b. Both systems contain a torque source, a gear with rotational inertia, J 1, supported by bearings with damping b1, a shaft with torsional stiffness, K, and a flywheel with rotational inertia, J 2, supported by bearings with damping, b 2. In System I, the gear is a spur gear, driven by a pinion with negligible inertia. In System II, the gear is a worm gear, driven by a worm with negligible inertia. The gear ratios of Systems I and II are the same: 20 rotations of the pinion, or worm, to one rotation of the gear.

Table P8.5 Parameter values for Systems I and II
Fig. P8.5a
figure 23

System I spur gear drive

Fig. P8.5b
figure 24

System II worm drive

There is one significant difference between the two systems. The spur gears of System I can be driven by either the torque source or the output shaft, K. However, the worm gears of System II can only be driven by the torque source. A worm drive is “self-locking.” It cannot be driven by its output shaft on the worm gear, only the input shaft on the worm.

The angular velocity of the pinion in System I need not have the same sign as the torque applied by the torque source. However, the angular velocity cannot have the opposite sign of the torque from the torque source. The angular velocity of the worm in System II can be of the same sign as the torque applied by the torque source or zero.

The spur gears are counter-rotating. Consequently, the angular velocities of the two shafts have opposite signs. We are free to define the signs for the rotation of the input and output shafts of the worm drive. For convenience, we will define the sense of rotation of the input and output shafts to have opposite signs to correspond to the rotation of the spur gear system.

  • 8.5.a Derive the state equations for Systems I and II.

  • 8.5.b The shaft, K, is carbon steel, solid with a circular cross-section, 2 in. in diameter and 12 ft long. Calculate its torsional spring constant, K, as described in Chap. 4.

  • 8.5.c The flywheel, J 2, shown in the plan and cross-section in Fig. P8.5.c, is carbon steel. Calculate the mass-moment of inertia (rotational inertia), J 2, using superposition, as described in Chap. 5. The spokes are 1 in. wide.

Fig. P8.5c
figure 25

Flywheel J 2

8.5.d Draw a flowchart of the logic needed in the state equation solver loop, to prevent “backwards” (positive) rotation of the worm gear, and to lock the worm gear, when the input torque is turned off.

The system is at rest and relaxed for \( t < 0, \) before an input torque pulse with magnitude of \( 10\,\,{\rm{N}} \cdot {\rm{m}} \)and a duration of one second is applied at time, t = 0, as shown in Fig. P8.5d.

Fig. P8.5d
figure 26

Input torque pulse

  • 8.5.e Write a MATLAB code to solve the state equations of System I with the Runge–Kutta algorithm for the pulse input shown in Fig. P8.3d. The duration of the simulation should be 2 s. Plot the state variables.

  • 8.5.f Modify the code to solve the state equations of System II, again plotting the state variables.

  • 8.5.g Calculate the maximum stress in the shafts of System I and System II. If the yield strength of the steel is 60 ksi, did either shaft fail?

Problem 8.6 A translational mechanical system contains a spring, two masses, and two dampers acted upon by an applied force is shown in Fig. P8.6a. The system has linear and non-linear configurations. There are two cases for both configurations. The two cases for the linear configuration of the system use the parameters in Table P8.6. The two cases of the non-linear configuration use the mass and spring constant values from Table P8.6, but have non-linear dampers which have half the damping coefficient b in extension as they do in compression, as shown in Fig. P8.6b. The values of damping coefficient b 1 and b 2 in Table P8.6 are the higher compression values for the non-linear dampers.

Table P8.6 Parameter values
Fig. P8.6a
figure 27

Third-order mechanical system

Fig. P8.6b
figure 28

Non-linear damper force, damper b 2 Case I. The damping coefficient in compression is that in Table P8.6. The damping coefficient in extension is one half of the tabulated value

  • 8.6.a Derive the state equations for this system.

  • 8.6.b Derive the output equations

    • i The velocity of mass M 1 .

    • ii The force acting through the spring K.

    • iii The velocity of mass M 2 .

    • iv The force acting through damper b 1.

    • v The force acting through damper b 2.

  • 8.6.c Express the state and output equations in matrix form.

  • 8.6.d For the linear configuration, calculate the system’s eigenvalues for Cases I and II. If the system is underdamped, determine the ideal, undamped natural frequency ω n , the damped natural frequency ω d, and the damping ratio ζ.

  • 8.6.e For Cases I and II of the linear configuration, write a MATLAB program to solve the state equations and the output equations for the force pulse plotted in Fig. P8.6c. Plot the responses of the output variables.

  • 8.6.f Edit a copy of the MATLAB program of part e to solve state and output equations of the non-linear configuration for Cases I and II. Plot the responses of the output variable to the force pulse of Fig. P8.6c.

Fig. P8.6c
figure 29

Input force pulse

Problem 8.7 A translational mechanical system contains a mass M sliding on a lubricating fluid film with damping b. The mass is acted upon by an applied force F(t). Spring K 1 is attached between the mass and ground. Spring K 2 is attached to ground but is not attached to the mass. When the system is at rest and relaxed, there is a gap of width d between Spring K 2 and the mass M. Spring K 2 and is only in contact with the mass when the position of the mass compresses spring K 2.

Fig. P8.7
figure 30

Second-order translational mechanical system

Two linear and one non-linear configurations of the system will be investigated. The two linear configurations are (1) Spring K 2 is absent from the system, and (2) Spring K 2 is attached to mass M. The non-linear configuration is that shown in Fig. P8.7 with gap d between the mass and spring K 2 when the system is at rest and relaxed. We will investigate two cases. (1) The gap d of the de-energized system equals zero, i.e. the spring is in contact with but not attached to the mass, and (2) the gap equals half the steady-state displacement of the mass under the load of 1,000 N. There are two sets of parameters, Case I and Case II.

Table P8.7 Parameter values
  • 8.7.a Derive the state equations for this system using K equiv as the spring constant.

  • 8.7.b Derive the output equations for:

    • i The velocity of the mass M.

    • ii The force acting through spring K.

  • 8.7.c Express the state and output equations in matrix form.

  • 8.7.d For the linear configuration, calculate the system’s eigenvalues for the parameter values of Cases I and II. If the system is underdamped, determine the ideal, undamped natural frequency ω n , the damped natural frequency ω d , and the damping ratio ζ.

  • 8.7.f Write a MATLAB program to solve the linear state equations using the Runge–Kutta algorithm for a step input force F(t) = 1,000 N u s (t). Assume the system is at rest and relaxed before the input acts on the system. Solve the output equations for the parameter values of Cases I and II and plot their responses.

  • 8.7.g Save your MATLAB script of part f under a different name and edit it to solve the non-linear state equations which include a gap between the mass and spring. Solve the state and output equations for the input and conditions of part f.

Problem 8.8 The schematic of an electric circuit with a voltage source, two inductors, two capacitors, a resistor, and a diode is shown in Fig. P8.8a.

Fig. P8.8a
figure 31

A non-linear RLC circuit

Table 8.8a Parameter values

Diodes conduct current only in the direction that the triangle of their symbol points Fig. 8.8b. This is a diode’s “forward” direction. Diodes have a threshold voltage which varies with the material and design of the diode. A typical silicon diode has threshold voltage of 0.63 VDC before it conducts in the forward direction, Fig. 8.8c. An actual diode’s voltage-current plot is similar to Fig. 8.8c. The small increase in resistance to the forward conduction with increased current is usually neglected and the diode modeled as having the threshold voltage drop but no additional resistance.

The system will be modeled in two configurations, a linear configuration without the diode, and a non-linear configuration with the diode.

  • 8.8.a Derive the state equations for the linear system and check their units.

  • 8.8.b Derive output equations for the following variables of the linear system.

    • i The voltage across capacitor C 1.

    • ii The voltage across capacitor C 2.

    • iii The current through inductor L 1.

    • iv The current through inductor L 2.

    • v The voltage across inductor L 1.

    • vi The voltage across inductor L 2.

    • vii The current through resistor R.

  • 8.8.c Write the state equations and output equations in vector-matrix form.

  • 8.8.d Calculate the linear system’s eigenvalues. If the system is underdamped, determine the ideal, undamped natural frequency ω n , the damped natural frequency ω d , and the damping ratio ζ.

Fig. P8.8b
figure 32

Diode schematic symbol showing forward direction (direction of current flow), c Diode voltage-current plot

The system is initially de-energized before the voltage pulse shown in Fig. P8.8d was applied.

Fig. P8.8d
figure 33

Input force pulse

  • 8.8.e Write a MATLAB program to solve the linear state equations using the Runge–Kutta algorithm for the voltage pulse input shown in Fig. P8.8d. Include the code to solve the output equations and plot their responses.

  • 8.8.f Save your MATLAB script of part e under a different file name and edit it to solve the non-linear state equations, which include the diode in the circuit, for the voltage input shown in Fig. P8.8d.

  • 8.8.g Compare the voltage across the inductances in the linear and non-linear systems and calculate the maximum change in voltage due to the diode.

Problem 8. 9 A cantilevered beam with rectangular cross-section is shown in Fig. P8.9a. Attached to the beam is a cylinder of mass M. The diameter of the cylinder equals the width of the beam w. The height of the cylinder is twice its diameter.

  • 8.9.a Determine the undamped angular frequency of the beam and mass system if they are carbon steel and L = 50 mm, w = 5 mm, and h = 1 mm.

  • 8.9.b Determine the damping coefficient b needed for the system to have a damping ratio of ζ = 0.04, using the velocity the point on the beam at distance L from the wall as the location of the velocity node. Determine the eigenvalues of the system.

Fig. P8.9a
figure 34

Linear cantilevered beam with a cylindrical mass attached at distance L from the support

8.9c The design is modified adding a support such that there is a gap d = 1 mm below the bottom surface of the beam, when the system is at rest and relaxed, at the distance of x = 30 mm from the support, Fig. P8.9b. When the beam is in contact with the support during downward deflection, approximate it as a cantilevered beam 20 mm long. The spring constant of the beam is greatly increased. Conversely, the effective mass of the beam is reduced when beam is in contact with the support.

The deflection equation for a point at distance x from the support of a cantilevered beam of length L is

$${{\delta }_{x}}=\frac{F{{x}^{2}}}{6EI}\left( 3L-x \right)$$

The area moment of inertia of a rectangular cross-section about a horizontal line through its centroid is

$$I=\frac{w{{h}^{3}}}{12}$$

Determine the effective mass and stiffness of the beam with the support as a function of the vertical displacement y of node 1, at the distance L from the wall.

Fig. P8.9b
figure 35

Support positioned under the beam at distance x from the wall and a gap d from the bottom of the beam when it is unloaded and at rest

  • 8.9.d Derive the state equations for this system.

  • 8.9.e Derive the output equations for:

    • i The velocity of node 1.

    • ii The force acting through the equivalent spring K.

    • iii The angular velocity difference across spring K.

  • 8.9.f Express the state and output equations in matrix form.

  • 8. 9 g.Write a MATLAB program to solve the linear state equations using the Runge–Kutta algorithm for a step input of F 0 = 10 N. Assume that the system was de-energized at time t = 0. Solve the output equations and plot the responses of the output variables.

  • 8.9.h Save your MATLAB script with a different file name and edit the script to include the effect of the support positioned under the beam. Run your program for the same input of F 0 = 10 N.

Problem 8.10 An electromechanical system is shown in Fig. P8.10a. A voltage source drives a DC motor, which has resistance R and torque constant K T . The DC motor turns a compliant shaft, modeled as a torsion spring with spring constant K. The shaft turns flywheel1 with mass moment of inertia J 1. Flywheel1 is supported on bearings with damping b 1. Flywheel2 has mass moment of inertia J 2 bearings with damping b 2, and is belt driven. A belt runs between flywheels one and two. The belt slips on the 4-in. diameter pulley when the force carried by the belt equals 20 N, limiting the maximum force in the belt to 20 N.

Fig. P8.10a
figure 36

Electromechanical system with a compliant shaft belt slip

Fig. P8.10b
figure 37

The compliant belt’s taut and slack sides switch positions during an oscillation.

Fig. P8.10c
figure 38

Linear graph representing a compliant belt as a translational spring between two rotational to translational transducer interfaces.

Table P8.10 Parameter values

The system model without belt slip is the linear model. The system model with belt slip is the non-linear model.

  • 8.10.a Derive the state equations of the linear model and check their units.

  • 8.10.b Derive output equations for the following variables:

    • i The current drawn from the voltage source.

    • ii The torque acting through the compliant shaft K 1.

    • iii The angular velocity of flywheel J 1.

    • iv The angular velocity flywheel J 2.

  • 8.10.c Write the state equations and output equations in vector-matrix form.

  • 8.10.d Calculate the system’s eigenvalues for the linear case with no belt slip. If the system is underdamped, determine the ideal, undamped natural frequency ω n , the damped natural frequency ω d, and the damping ratio ζ.

The system was de-energized before a step input of 48 VDC was applied.

  • 8.10.e Write MATLAB code to solve the state equations and output equations of the linear model with the Runge–Kutta algorithm for the step input of 48 VDC. Plot the responses of the output variables.

  • 8.10.f Save the MATLAB script of part e under a different name and edit the code to solve the state equations and output equations of the non-linear model for the step input of 48 VDC. Plot the responses of the output.

Chapter 8 Appendix

8.3.1 Introduction to Programming and MATLAB

Why study computer programming, if engineering software is available? Further, the sophisticated computer programs used in engineering design and analysis are enormous. They often required teams of programmers and years to develop. What can an individual engineer and novice computer programmer accomplish of value? Fortunately, one does not need to be an expert programmer to write useful computer programs. A little knowledge of computer programming goes a long way.

Competent engineers must be able to write simple computer programs for data acquisition and reduction, as well as design computations. It is helpful to know some common programming syntax and techniques, since they appear in many user interfaces. An understanding of the fundamentals of computer programming is important to maximize the utility of most engineering software. Most engineering software packages allow the user to write either “macros” or “scripts,” which are short programs, to automate repetitive processes or iterative computations.

Computers are not only an important tool in the design process. Microprocessors are now widely used as “embedded” controllers in machines. Microprocessors are microcomputers which contain the central processing unit (or CPU which performs arithmetic and logical operations on data), memory, and input and output devices on a single chip. Now that microprocessors capable of machine control cost less than one dollar, only the simplest machines are purely mechanical. A machine’s functionality can be enhanced, and its performance improved, by microprocessor control. A machine designer must understand the basics of how microprocessors function, to understand the machine they are part of.

8.3.2 A Brief History and Classification of Computer-Programming Languages

Computer programming languages have evolved to meet the changing demands of users. The very first computers were programmed in a “machine-level” language, which specified how to implement each individual step required to manipulate the data. Machine-level “code,” or “instructions,” are at the level of detail needed to describe a complicated hand-held calculator computation, i.e., recall x, recall y, add x and y, store the result in z, etc. The instructions, however, are in binary code, since the computer’s digital circuitry functions with 0’s and 1’s. The computer machine code equivalent to a calculator’s “recall” is “move data,” which is the operation of reading data at a location in memory, and writing it to a different location. Typical machine code for the operation, “move data,” is the four-digit binary code, 1011. Binary code is difficult for humans to work with. The codes, 1101, 1011, and 1110, are different instructions. It was not long before the second-generation computer languages, called “assembly languages,” were created. Assembly languages use an alphanumeric code in place of binary code, making them much easier for humans to understand. The alphanumeric code incorporates three-letter abbreviations for the machine’s operations. For example, MOV is the assembly code for “move data” and MUL is the assembly code for “multiply.” The most important memory locations, known as registers, are given alphanumeric codes, such as AX and B1. Octal (base 8) or hexadecimal (base 16) can be used in place of their 8, 16, or 32 binary-digit addresses.

Assembly language code is still commonly used to program the small microprocessors used for machine control. It was superseded for general use in the early 1950s, however, when FORTRAN (an acronym for FORmula TRANslation), the first of the third-generation computer languages, was introduced. FORTRAN was the dominant program for engineering computations through the mid-1970s. FORTRAN is now known as a “procedural” language. The syntax and structure of a procedural computer language are oriented towards algorithm, i.e., the logic of the computation. Early procedural languages include ALGOL (ALGOrithmic Language, mid-1950s), COBOL (COmmon Business Operations Language, late 1950s), LISP (LISt Processing language, early 1960s), and BASIC (Beginner’s All-purpose Symbolic Instruction Code, mid-1960s). BASIC was implemented as an “interpreted,” rather than a “compiled,” language. An interpreted language is converted into machine code line by line, as the program executes. Compiled languages are converted into machine code, before the program executes. Compiled programs run significantly faster than interpreted programs. Procedural languages remain sufficient for programming engineering computations. FORTRAN was last revised in 2008. LISP is used in Autocad. The current manifestation of BASIC is Microsoft’s Visual Basic 2013.

Two diametrically opposed trends impacted the development of computer languages in the late 1960s. Computer programs increased in size, while computers themselves decreased in size. Computer scientists found that some aspects of early procedural languages became unmanageable, as programs grew in size and were written by teams of programmers. Pascal (mid-1970s) was the first of the new “structured” programming languages. Structured programming languages modularized a large programming task into a set of smaller tasks, and provided a structure for the modules to interact. Modularizing the program code also allowed for easier reuse of portions of the code in other programs. Simultaneously, “minicomputers” using newly developed integrated electronics provided low-cost competition to large and expensive “mainframes.” These smaller computers prompted a minimalist approach to developing applications to run on them. The language C (early 1970s) is a procedural language with an enriched set of operators. C also provides access to bit-level operations, formerly only possible using assembly language. C remains an important language today. Many microprocessors programmable in assembly language are also programmable in C. Although the richness of C permits arcane programming practices, it is also possible to program in C in a style close to FORTRAN, BASIC, or MATLAB. C is an “open source” language, meaning it is available for free.

Current programming languages are “object-oriented,” as opposed to the earlier procedural-oriented programming languages. The intent of object-oriented programming is to create modular and “encapsulated” code, where “encapsulation” means that the code can safely be used in a modern Windows-based program with millions of lines of code, without causing conflict with other portions of the program. In the abstract, the modern, enormous computer programs can be written in the early procedural languages. In practice, however, developing and debugging gigantic programs written in procedural languages would result in software overpriced and obsolete, by the time it went to market.

Object-oriented programming languages focus on the data, not on algorithms. At first, this sounds impossible. Of what use are data without algorithms to manipulate and interpret them? Object-oriented programming languages package the algorithms needed into a module called a “class,” specific to each type of data, or “object,” in the program.

A familiar example of a data type is a complex variable. Complex variables are manipulated differently from real variables. The addition operator for real variables is part of the programming language. The algorithms to create an addition operator for complex variables would be part of the class, “Complex.” The class, Complex, would include other properties, such as calculation of the magnitude, and operations, such as multiplication and division of complex numbers. The class, Complex, would be added to any program which includes complex variables. Each complex variable used in the program would be an “object.”

The first widely adopted object-oriented programming language was C++ (early 1980s). C++ was developed from C. C programs can run in most implementations of C++. Today, C++ seems to be the dominant language used in academic research. Microsoft gives away stripped-down versions of C++, and its modernized version, called C#, with no multi-core support or 64-bit math. C# has simpler syntax than C++. Unfortunately, object-oriented languages are more difficult to learn than procedural languages. There is twice as much to understand. Object-oriented languages have all of the syntax and operators for their procedural aspect, plus as much again in syntax and operators for their object-oriented aspect.

We will work with the programming language, MATLAB. MATLAB is a “high-level” programming language developed for engineering and scientific applications. “High level” means that many of the tasks, which must be programmed in other languages, are performed automatically in MATLAB. Specifically, all of the mathematical functions you can imagine, along with an engineer-friendly plotting function, are provided. MATLAB is an interpreted not compiled language. It runs slowly, compared to C or C + + . Further, an academic license limits MATLAB in ways which can affect the accuracy of computations. However, programs will be fairly simple, as well as run quickly and accurately enough for our purposes.

8.3.3 Fundamentals of Procedural Programming

One purpose in learning procedural programming is to automate numerical methods that were developed in the late 1800s and early 1900s, before the invention of the digital computer. The algorithms were initially implemented using “desk calculators,” which could add and multiply. The early desk calculators were purely mechanical, crank-operated devices, which later evolved into electromechanical designs. They were enormously complex and quite expensive. The cost and complexity of these machines stimulated the design of purely electronic calculators, which led to the invention of the microprocessor.

Computer programs are instructions “coded” in the syntax specific to a particular computer language. Dozens of computer languages exist. Different computer languages were written to provide convenient methods of performing certain tasks, such as creating attractive graphical user interfaces, manipulating strings of characters, or performing numerical calculations. Although computer languages can be very different, there are fundamental, logical, and mathematical entities and operations which are common to all computer languages.

Three fundamental functions must be performed by a computer to execute an engineering algorithm.

  1. 1.

    Store and retrieve data.

  2. 2.

    Evaluate conditional statements comparing the values of two variables.

  3. 3.

    Perform arithmetic operations.

We will focus on these fundamental aspects of programming. Our development will begin with a brief overview of the physical and logical design of data storage. We will then introduce “flowcharts” as a technique for graphical presentation of programming logic. Our first programming will use the TI-89 calculator. This is historically appropriate, since Texas Instrument introduced some important mid-scale integrated circuits in the late 1960s. We will then move to MATLAB, a powerful high-level language. Finally, we will compare MATLAB and the programming language, C.

8.3.4 A Brief History of Computer Memory

Data are stored in the computer’s memory, exploiting a physical phenomenon or device, which can exist in one of two states (such as off or on; low or high; open or closed; de-energized or energized; etc.), associated with the binary digits, 0 and 1. The earliest digital computers built during World War II used vacuum tubes, or electromechanical relays as memory elements, where the state of the device represented a binary digit, or “bit.” Vacuum tubes and electromechanical relays were eventually replaced by “reed” relays, which are still commercially available. Reed relays are pairs of very thin steel cantilevers sealed in tiny glass vials. A coil around the vial closes the contacts. Vacuum tubes consume a great deal of power with lower reliability than reed relays, but they “transition,” or change states, faster. Memory devices after World War II included “delay lines,” devices which use the propagation time of a wave through a media to store information, such as an acoustic wave through mercury; and “drum memory,” similar in function to current hard disk memory but with a small fraction of the capacity and read, write, and erase heads for each track.

Discrete (as opposed to integrated) transistors and “magnetic core” memory took the place of vacuum tubes in the 1950s. Core memory was the dominant form of computer memory in the late 1950s through the early 1970s, and is still used in a few military and aerospace applications for its reliability in extreme conditions. Core memory is a rectangular grid of orthogonal wires with tiny rings, or cores, of a ferromagnetic material at the intersections. Currents through two wires magnetize the core at their intersection in either a clockwise or counter-clockwise direction, depending on the direction of the currents. The direction of magnetic flux in the core is defined as 0 or 1. Discrete memory was replaced by integrated circuits, beginning in the late 1960s. The density of integrated circuits, as measured by the number of transistors per unit area, has approximately doubled every two years.

8.3.4.1 Bits, Bytes, and Words

We now consider the basic structure of computer memory. The smallest element of computer memory is a single BInary digiT, a bit. Groups of eight bits are called “bytes.” Bytes are elements of “words.” Microprocessors have fixed word sizes from 8 to 32 bits in length, which increase with the cost of the microprocessor. Current personal computers can have words up to 64 bits in length, but vary the size of words used, to make best use of memory. We will assume a 16-bit word comprising two 8-bit bytes, which is the size of words in many mid-level microprocessors used in machine control. Further, we will only discuss microprocessors to focus on the basics, and avoid the complexity of the clever addressing schemes used by computers.

In order to store data in and retrieve data from a computer’s memory, there must be an “address” , a unique name, for each word. The number of words, which can be addressed using N binary bits, equals the maximum value of binary number of N bits—in other words, a binary number of N bits, each of which is 1

$$Number\,\,of\,\,Addresses=\sum\limits_{n=0}^{n=N-1}{{{2}^{n}}}={{2}^{N}}-1$$

Example: The number of words which can be addressed with an 8-bit word is:

$$\begin{aligned} & Number\,\,of\,\,Addresses={{11111111}_{2}} \\ & \quad \quad \quad \quad\quad \quad \quad \quad \quad \quad \quad \quad \quad \quad\quad \quad \quad \quad =\sum\limits_{n=0}^{n=8-1}{{{2}^{n}}}={{2}^{0}}+{{2}^{1}}+{{2}^{2}}+{{2}^{3}}+{{2}^{4}}+{{2}^{5}}+{{2}^{6}}+{{2}^{7}} \\ & \quad \quad \quad \quad\quad \quad \quad \quad \quad \quad \quad \quad \quad \quad\quad \quad \quad =1+2+4+8+16+32+64+128=255={{2}^{N}}-1 \\\end{aligned}$$

The number of words which can be addressed by a 16-bit binary number is \( {2^{16}} - 1 = 65,536 - 1 = 65,{535_{10}}. \) Sixteen-digit binary numbers are difficult to work with. The hexadecimal equivalent is used instead.

$${{1111111111111111}_{2}}=FFF{{F}_{16}}$$

A common notation for addressing a bit within a byte or a word is to number the bits from the least significant bit (LSB), to most significant bit (MSB). For example, the bit addresses in a 16-bit word range from 0 for the LSB, to F for the MSB expressed in hexadecimal.

The bit number is appended to the word address after a dot. For example, the address of the MSB in the 16-bit word with the address, 352A, is 352A.F. The bit address, 352A.F, is not a binary fraction. It is an address code. The dot is not a radix. It is just a dot.

8.3.4.2 Binary, Octal, and Hexadecimal Numbers

The “base” of a number system is the number exponentiated to yield the place values of that system. Decimal is base 10. Binary is base 2. We will also work with octal , which is base 8, and hexadecimal, which is base 16. We write numbers using “positional notation,” which we commonly refer to as “place value.” In a decimal number, the decimal point, or radix, marks the division between place values with exponents less than zero, and place values with exponents greater or equal to zero

Fig. A8.1
figure 39

A sixteen-bit word is composed of two 8-bit bytes

Table A8.1 Decimal place values, including natural decimal fractions

“Natural” decimal fractions are the place values to the right of the radix. The only decimal fractions which are exact are those which can be represented by sums of the natural decimal fractions. For example,

$$\frac{1}{2}=\frac{5}{10}=\frac{1}{10}+\frac{1}{10}+\frac{1}{10}+\frac{1}{10}+\frac{1}{10}=0.5$$

is an exact decimal fraction, whereas

$$\frac{1}{3}=\frac{3}{10}+\frac{3}{100}+\frac{3}{1,000}+\frac{3}{10,000}+\frac{3}{100,000}\cdots +\frac{3}{{{10}^{n}}}+\cdots =0.\overline{333333}$$

is not an exact decimal fraction, since it cannot be expressed as a finite sum of natural decimal fractions.

Positional notation is used within all number systems, including binary. Although the term, “binary point,” is commonly used in the United States, the proper term is “radix .” Integer binary place values are to the left of the radix. Natural binary fraction place values are to the right, just as with decimal numbers. Natural binary fractions and their decimal equivalents are familiar, because US customary units use fractions which are powers of one half.

Table A8.2 Binary place values from 2–4 to 25

The place values for the first 16 binary digits to the left of the radix, expressed as decimal numbers, are

Table A8.3 Binary place values from 215 to 20

Octal (base 8) was used to address memory in early computers which had very little memory. Programmable logic controllers (PLCs) still use octal (base 8) for addressing memory, because they need relatively little.

Table A8.4 Octal place values from 87 to 80

Hexadecimal (base 16) is used in modern computers, because it allows large numbers to be represented easily, and converts easily and exactly to binary. The decimal number system has 10-digit symbols, zero through nine, and the hexadecimal system needs 16-digit symbols, zero through fifteen. The hexadecimal digit symbols for the decimal numbers, 10 through 15, are the Roman letters, A through F.

Table A8.5 Hexadecimal digits

8.3.5 Base Conversion

Base conversion allows one to represent a given number in different number systems. It can always be accomplished by performing successive division, starting with the largest divisible place value, and working down in place value. The process is repeated on the remainder of the each division, until the conversion is carried to the precision desired.

We will illustrate the technique by converting the decimal number, 47.8, into binary number, using the binary place values from 25 to 2–4. The decimal number, \( 32 = {2^{\,5}}, \) is divisible, leaving a remainder of 15.8. The next binary place value, \( 16 = {2^{\,4}}, \) is not divisible. The process is repeated.

figure q

The results are

Binary Place Values

2 5

2 4

2 3

2 2

2 1

Dividend

47.8

15.8

15.8

7.8

3.8

Divisor

32

16

8

4

2

Division possible?

Yes

No

Yes

Yes

Yes

Binary Digits

1

0

1

1

1

Remainder

15.8

15.8

7.8

3.8

1.8

Binary Place Values

20

2−1

2−2

2−3

2−4

Dividend

1.8

0.8

0.3

0.05

0.05

Divisor

1

0.5

0.25

0.125

0.0625

Division possible?

Yes

Yes

Yes

No

No

Binary Digits

1

1

1

0

0

Remainder

0.8

0.3

0.05

0.05

0.05

Yielding the conversion from decimal to binary

$${{47.8}_{10}}={{101111.1100}_{2}}$$

Note the error of 0.0510 between the binary and decimal numbers, even though the base conversion was to four binary places to the right of the radix. It is always possible to perform an exact conversion of integer values between bases. However, it is often impossible to convert fraction values between bases exactly.

A second example: Convert 978 (base 10) to octal (base 8). First, determine the octal place values in base 10 to a sufficiently large value to perform the division.

Perform successive division on the number to be converted to octal, 97810

figure r
 

84

83

82

81

80

Base 10 Divisors

4,096

512

64

8

1

Value of 97810 in Octal

0

1

7

2

2

The result is 97810 = 17228. The method of successive division always works, but is not necessary when one is converting between number systems that are powers of a common base, such as binary (base 2 = 21), octal (base 8 = 23), or hexadecimal (base 16 = 24). There is a shortcut.

Numbers can be converted among binary, octal, and hexadecimal by exploiting the power relationship between the bases. Compare the place values of binary, octal, and hexadecimal:

figure s

The relationship between the nth octal place value and the corresponding binary place value is 8n = (2n)3. Similarly, the relationship between the n th hexadecimal place value, and the binary place value is 16n = (2n)4. Consequently, it requires three binary digits, or places, to represent an octal number, and four binary digits to represent a hexadecimal number. The shortcut is to convert the number to the common base, binary in this case, and then to either octal or hexadecimal base, by separating the binary number into groups of three or four binary digits, respectively, and converting the binary group into a single digit in the higher base.

Example. Express the decimal number, 935, in binary, octal, and hexadecimal. Base 10 does not share a common base with base 2, base 8, or base 16. The conversion from decimal to binary must be accomplished by successive division, as above. Summarizing the result, the binary value of 93510 is

figure t

We can now readily convert to octal, by dividing the binary number into blocks of three binary digits. Then sum each block of three binary digits to yield its octal value

figure u

Likewise, we can convert from binary to hexadecimal, by dividing the binary number into blocks of four digits. Sum them to yield their hexadecimal value.

Now, convert from binary to hexadecimal:

figure v

Summarize the decimal, binary, octal, and hexadecimal values:

93510 = 11101001112 = 16478 = 3A716.

8.3.6 Computational Error on Conversion from Natural Decimal to Natural Binary Fractions

As we have seen, integer values can be converted between different bases exactly. However, fractional values may be impossible to express exactly within a base. If they can be expressed exactly within one base, we may not be able to express them in a second base. We touched on the computational error inherent in conversion between decimal and natural binary fractions above. It is an important topic, which deserves elaboration.

Natural binary fractions can be expressed exactly as decimal fractions, if enough significant figures are used. Example:

$$\frac{1}{64}=\frac{0}{10}+\frac{1}{100}+\frac{5}{1,000}+\frac{6}{10,000}+\frac{2}{100,000}+\frac{5}{1,000,000}=0.015625$$

However, beware, it does not work the other way. Most natural decimal fractions cannot be expressed exa ctly as binary fractions! For example, we can approximate \( {\frac{1}{{10}}_{10}} \) as

$$\begin{aligned} & \left( \frac{1}{{{16}_{10}}}+\frac{1}{{{32}_{10}}} \right)<\frac{1}{{{10}_{10}}}<\left( \frac{1}{{{16}_{10}}}+\frac{1}{{{32}_{10}}}+\frac{1}{{{64}_{10}}} \right) \\ & \\ & \quad \quad \quad {{0.000110}_{2}}<{{0.1}_{10}}<{{0.000111}_{2}} \\ & \\ & \quad \quad \quad {{0.09375}_{10}}<{{0.1}_{10}}<{{0.109375}_{10}}. \\\end{aligned}$$

Note additional binary places do not solve the problem. Also, binary fractions may appear smaller than their corresponding decimal fractions, but they are not.

Example. Suppose you have a timer, timing by one hundredth of a second by summing the equivalent binary fraction. How much error would you accumulate in an hour? First, we have to choose our binary fraction approximation of \( \frac{1}{{{{100}_{10}}}} \)

$$\begin{array}{*{20}{c}} {\frac{1}{{{{128}_{10}}}} < \frac{1}{{{{100}_{10}}}} < \left( {\begin{array}{*{20}{c}} {\frac{1}{{{{128}_{10}}}}}+{\frac{1}{{{{256}_{10}}}}} \end{array}} \right)} \\ {{{0.0078125}_{10}} < {{0.01}_{10}} < {\text{0}}{\text{.01171875}}{{\text{0}}_{10}}} \\ {{{0.000000010}_2} < {{0.01}_{10}} < {{0.00000011}_2}.} \end{array}$$

Both available approximations have substantial error:

$$\begin{aligned} & {{0.0078125}_{10}}-{{0.01}_{10}}=-\text{0}\text{.00218750}{{\text{0}}_{\text{10}}} \\ & \\ & \text{0}\text{.01171875}{{\text{0}}_{10}}-{{0.01}_{10}}=\text{0}\text{.00171875}{{\text{0}}_{\text{10}}}. \\\end{aligned}$$

Using the approximation with less error per count, \( {0.01_{10}} \approx {0.00000011_2}, \) in 1 h, the accumulated error is

$$\left( \text{0}\text{.00171875}{{\text{0}}_{\text{10}}}\frac{\operatorname{sec}\,\,error}{count} \right)\left( 100\frac{counts}{\operatorname{sec}} \right)\left( 60\frac{\operatorname{sec}}{\min } \right)\left( 60\frac{\min }{h} \right)=618.75\,\,\frac{\operatorname{sec}\,\,error}{h}$$

Clearly, simply summing the binary fraction approximation of a decimal fraction is an unacceptable timing algorithm. Sadly, many engineering errors have been made through ignorance of the magnitude of the error, in converting between natural decimal fractions and natural binary fractions. These errors could have been prevented by using natural binary fractions, which can be converted to decimal fractions exactly.

Data Types

The binary numbers used for word addresses are positive binary integers. How does a computer store negative binary integers or “real” binary numbers, i.e., binary fractions? Also, how are large numbers, those greater than 2N  − 1, stored? They are coded, and in order for a computer to manipulate numerical data, it must know the coding, known as the “data type,” associated with the data, in a specific word (or words) in memory. Some languages will assume a default data type, if the programmer does not “declare” a variable to be a certain data type. Other languages will not compile a program, if all variables used are not declared and assigned initial values. The discussion that follows is general, since the specific term used for a generic data type, and the number of bits associated with it, varies with both computer and programming languages.

8.4.1 Integer and Signed Integer Variables

The simplest data type is a positive binary integer. No coding is needed, other than to associate place value with location within a word, since increasing numbers of bytes can be used to store integers. Various adjectives and acronyms are used to distinguish between lengths of the integer data types. (An example of awkward terminology is C++ ’s “long long integer” which is, as you would expect, longer than C++ ’s “long integer”.)

The “signed integer” data type requires coding to distinguish between positive and negative values. The sign of the integer is represented by setting the most significant bit (MSB) to 1, to indicate a negative number. Negative numbers are stored in two’s complement form. Two’s complement form is created in two steps. First, every bit in the number, except the sign bit, is inverted. If a bit is 0, then it is changed to 1. If a bit is 1, then it is changed to 0. Next, the number, 1, is added to the number.

Example. Create the two’s complement of the binary number, − 1101011, by using a 16-bit word.

Sign bit (MSB) set to 1, followed by the binary number, 1101011:

$$1000000001101011$$

Bits 0 through E are inverted:

$$1111111110010100$$

One is added to create the two’s complement:

$$1111111110010101$$

We will test the usefulness of two’s complement by performing the addition, − 1101011 + 1101011, which should yield zero:

$$\begin{array}{l} 1111111110010101{\mkern 1mu} {\mkern 1mu} {\mkern 1mu} \leftarrow {\mkern 1mu} {\mkern 1mu} Two's{\mkern 1mu} {\mkern 1mu} complement{\mkern 1mu} {\mkern 1mu} of{\mkern 1mu} {\mkern 1mu} 1101011\\ + \frac{{{\rm{0000000001101011}}}}{{{\rm{0000000000000000}}}} \end{array}$$

8.4.2 Floating Point Variables

“Floating point ” is the term used by computer scientists for scientific notation, i.e., the product of a decimal fraction between 1 and 10, and a multiplier which is a power of 10. Varying the exponent has the effect of moving the radix or decimal point, hence the term floating point. The coding of floating point numbers is more involved than for signed integers, since both the mantissa and the exponent are signed. We will not delve into details, other than to note that more bits are allotted to the mantissa than the exponent. For example, if the floating point data type was 4 bytes or 32 bits long, the mantissa may be 24 bits and the exponent 8 bits. “Double” is a common name for the data type with twice, or double, the internal storage and, hence, numerical precision of the floating point data type.

Computer code is restricted to the characters of a keyboard. Consequently, the product of the decimal fraction multiplied by the power of 10 is expressed, omitting the base of 10 and preceding the exponent of 10 with E (or e) for “Exponent,” e.g.,

$$352.478\,\,\,\,\,\,\to \,\,\,\,\,\,3.52478\times {{10}^{2}}\,\,\,\,\,\,\to \,\,\,\,\,\,3.52478\,E\,02\,$$

8.4.3 Boolean or Logical Variables

Boolean variables , also known as “logical” variables are a late addition to programming languages. They are unnecessary, since one can use integer variables with values of either 0 or 1 in their place. They were added to programming languages to prevent errors that result from integer variables, which were to be restricted to the two Boolean states, being accidently assigned other values.

Procedural Logic and Flowcharts

The numerical methods used in engineering can be very sophisticated. Some required decades to reach their current form. Fortunately, writing a computer program to implement an existing numerical method is far less of a challenge. Most of the effort is spent in developing an understanding of the numerical method, before the program is written, then searching for any coding errors afterwards.

Flowcharts are a graphical representation of the sequence, in which the instructions of a program are to be executed. Although not all types of programs can be depicted in a flowchart , our programs can. A flowchart presents the logic of a program, without the details of the specific programming language syntax. Flowcharts serve the same function for computer programs, as outlines serve for papers. Flowcharts show the flow of “logical control” through an algorithm. They consist of “blocks,” which contain instructions or operations, and arrows connecting the blocks to indicate the flow of logical control.

Rectangular blocks are “executable” blocks, which represent actions or calculations. The action or calculation may be a single, simple step, or it may be many complicated steps. The action or calculation may be vaguely described in English or expressed explicitly in mathematics. There can only be one logical path entering the block and only one logical path exiting the block. The direction of the logical flow is indicated by arrows.

Fig. A8.2
figure 40

An “executable” block represents an action or calculation

Diamond-shaped blocks are “decision” blocks, per Fig. A8.3. They contain conditional statements, i.e., greater than, less than, equal to; or a Boolean or Logical variable; or a result which must be either True or False. There can only be one

Fig. A8.3
figure 41

The standard diamond-shaped decision block

Fig. A8.4
figure 42

An alternative, non-standard, decision block

Fig. A8.5
figure 43

A logical loop. “Control” exits the loop, when the condition expressed in the diamond-shaped decision block is satisfied

logical path into the decision block . There are two logical paths which exit. Each path must be identified by the logical result or value it represents, i.e., Yes or No; True or False; etc. The logical flow “branches” at decision blocks. The exit from the decision block taken by the logical control is governed by the result of evaluating the conditional statement, value of the Boolean variable, or logical result. A diamond shape is standard for a decision block, but that shape can become cramped for long expressions. This text will also use, as needed, a non-standard, “alternative style,” decision block, per Fig. A8.4.

8.5.1 Logic Loop

An important use of a decision block is to form a “loop,” per Fig. A8.5. A loop is a logical path that passes through the same blocks more than once. Loops are used for repetitive calculations. The instructions within the loop are executed repeatedly, either for a fixed number of times, or until a logical condition is satisfied. If the programmer errs and neglects to create an exit condition, or creates an exit condition that is impossible to satisfy, then the logic is trapped in an “endless loop.”

8.5.2 Nested Loops

It is common to use “nested” loops with one loop inside another, Fig. A8.6. Each loop has a counter variable. The inner loop’s counter variable must complete its index through its range for the outer loop’s counter variable to index once nested loop are useful for working with arrays and matrices.

8.5.3 Flowchart Rules and Guidelines

Although an international standard for flowcharts exists, there is no reason to abide by it, when drawing flowcharts for one’s own use. There are two rules, which must be respected for the flowchart to be logical.

  1. 1.

    There can only be one logic path leaving a block, except decision (diamond) blocks which have Yes and No or True and False paths.

  2. 2.

    Branching can only occur at a decision block.

The following are a few guidelines which will eliminate errors and improve the readability of flowcharts.

1. Every block in the diagram should be on at least one logical path from the Start block to the Finish block. If a block cannot be reached from the Start block, then the instructions in that block will never execute. If the path from a block does not eventually reach the Finish block, then the logic will never properly terminate. A common error is to terminate a path at a result or action, other than Finish.

Fig. A8.6
figure 44

Nested loops

Fig. A8.7
figure 45

Flowchart with illogical branching occurring outside of a decision block. No logical conditions for the branching are shown

  1. 2.

    Have only one path into a block. If there are multiple paths leading to the block, have them join at a node before the block, then have a single path into the block.

  2. 3.

    Draw the logic, so that sequential blocks are arranged from top down, or side to side. Do not arrange sequential blocks to read from bottom to top.

The following flowcharts, A and B, Figs. 8.11 and 8.12, illustrate the use of a decision block to control the number of times that logic loops through a set of instructions. In both flowcharts, a “counter” variable, n, is assigned the value of one before the logic enters the loop. The loops in both flowcharts contain identical instructions. The first instruction in both loops computes the output variable, y, by squaring the counter variable, n. However, the order of the two remaining blocks is different in the two flowcharts. In Flow Chart A, the counter variable, n, is “incremented,” or increased, by one with the instruction:

$$\rm n=\rm n+1$$

before the logic enters the decision block with the relational expression, n = = 10? In Flow Chart B, the logic enters the decision block and evaluates the relational expression, n = = 10?, before the counter is incremented.

Fig. A8.8
figure 46

Flowchart with dead-end logic

Fig. A8.9
figure 47

aTwo branches entering one block, logical but can be difficult to read b Preferred flowchart. Flow merges at a node before entering the block

Fig. A8.10
figure 48

Flowchart with upside down flow: logical, but difficult to read and, therefore, error prone

The program shown in Flow Chart B will loop 10 times, as n is incremented from \( n = 1 \) to \( n = 9. \) When \( n = 9, \) the program terminates. The program shown in Flow Chart B will loop 10 times, as n is incremented from \( n = 1 \) to \( n = 10. \) When \( n = 10, \) the program terminates.

The effect of the relative position, where the counter variable is incremented within the loop, and the relational expression, which terminates execution of the loop, is straightforward. It is a very common error, however, to have a loop execute one more time, or one fewer time, than the engineer intended.

MATLAB

Modern programming languages provide an “environment ,” which is a desktop and a set of windows. The menu, “Desktop,” contains items which allow you to open needed windows. We will use the “Command” window and the “Editor” window. MATLAB retains the configuration of the environment when the program is closed, and returns to that configuration when it is started up. In a multi-user location, such as a computer lab, the MATLAB “environment” (or set of windows), when opened, will reflect the preferences of the previous user.

Fig. A8.11
figure 49

Flow Chart A

8.6.1 MATLAB “Environment”

The MATLAB “environment” includes the Command window, the Editor window, and the Help window, among others. The Editor is well hidden. MATLAB’s Editor opens, when the user clicks on the New Script button. A script is a short program. The term, script, came into use after the size of programs became enormous. Scripts, or programs, are written in the Editor window, saved as an “m-File” (a file with extension file_name.m), and then run from the Command window. MATLAB does not permit spaces in file names.

MATLAB looks in a number of locations to find m.files, including the default directory. The collection of directories and folders checked for m.files is known as MATLAB’s path. If you write a script and attempt to save it to your flash drive, you will see a MATLAB message stating the folder is not in MATLAB’s path, and ask if you would like to add it. Accept this choice, so that MATLAB will look at your flash drive for a script.

Fig. A8.12
figure 50

Flow Chart B

A MATLAB program is run, by typing the name of the m-file without the extension, “.m,” at the prompt in the command window. Example: If you have an m-file named Model5.m, run the program by typing only Model5.m, at the prompt in the command window. MATLAB will look in its default directories to find the m-file. Consequently, when you open MATLAB on a public computer, click on the Set Path button in the Environment tab, and add your flash drive folder to the path. If you forget to do this, and you have chosen a common name for your script, then MATLAB may find someone else’s script of the same name saved to one of its default directories, and run that one instead. It may take a while to recognize that script is not yours, particularly if you failed to add comments.

MATLAB is an interpreter, meaning, it will happily execute a script, or the same commands entered at the prompt in the Command window. The variables used during a work session are retained, until the program is closed. They are displaced in the Workspace window. Retention of previous variables is very convenient, when you are using MATLAB as a calculator, and entering computations at the Command window prompt. Once you have defined a variable, you may use it for the entire work session.

However, there is a dark side to MATLAB’s workspace. The existence of variables in the workspace can mask errors and omissions in scripts. For example, suppose you write a script to calculate a response function. You intend to define a variable named tau as being equal to a certain value, but you simply forget, and omit that line of code. If you run the script, and tau was not used in any previous calculations, so that it is not in the workspace, MATLAB will identify the error. A ding sounds. The Command window contains an error message, indicating that an undefined variable was used in line x of the script. On the other hand, if you omit the definition of tau in the script, but another tau already exists in the workspace, MATLAB will use the workspace value. The script will execute but produce an erroneous result.

Engineers tend to use and reuse the same meaningful variable names. MATLAB does not create a new instance of an existing variable. So if a MATLAB execution error occurs, or the results of a successful execution of a script don’t make sense, clear the workspace, and run the script again. The entire workspace is cleared by selecting the title bar of the Workspace window, right-clicking, and choosing Clear Workspace. Individual variables are deleted, by selecting the variable in the Workspace window, right-clicking, and choosing delete. MATLAB’s retention of variables is a particular nuisance, when debugging a script. It is common to change the number of iterations within a for loop, while debugging. When results of a computation are written to a vector, or an array, and the number of iterations is increased, no problem. If the number of iterations is decreased, the values beyond the most recently overwritten elements are unchanged. A plot may make sense, nearly to the end, before becoming quite strange. When faced with inexplicable results, clear MATLAB’s workspace first, before tearing apart your script.

8.6.2 Variables

MATLAB does not require variables to be “declared,” meaning the types of data assigned to variables do not have to be identified before they are used. Integer and floating point variables are identified by their use. Integer variables are assigned integer values, i.e., numbers without a decimal point. Floating point variables are assigned either decimal numbers or numbers expressed in scientific notation.

All variables must have a name. In MATLAB, variables names must begin with a letter and may contain numbers and underscores, but no other special characters. MATLAB is case sensitive.

Values are assigned to variables with an “assignment” statement. The assignment operator in MATLAB is the conventional equal sign, =. Type the following statement in the Command window to assign the value of 3.5 to the variable “mass.”

figure w

An assignment statement assigns the value of the right side to the variable named on the left side. Assignment statements are not equations! Typing the statement in the reverse order (capitalizing the “M” in Mass to make it a different variable) produces an error.

figure x

MATLAB thought you tried to name a variable, 3.5. This violates two of its rules: (1) variable names must start with a letter, and (2) the only permissible non-alphanumeric character is an underscore. Periods, points, or dots are not permitted in variable names.

Variables can be assigned strings of characters. Characters or strings of characters are identified by pairs of single quotes. Example: type the following valid assignment statement

figure y

Note how MATLAB color-codes the input as you are typing. When you type the lead single quote, MATLAB highlights the single quote and the following characters in dark red, until the closing single quote is typed. It then changes the color to purple to indicate the expression is complete.

Logical variables are defined by assigning a value of either true or false to the variable. MATLAB recognizes true as equivalent to the Boolean value 1, and false as equivalent to the Boolean value 0. When you type

figure z

MATLAB echoes

figure aa

Many computer languages will not allow you to use a logical variable in a numerical calculation. MATLAB is more forgiving. Type

figure ab

and you will find the result is 4.5000.

8.6.3 Scalar, Matrix, and Array Variables

MATLAB was written to facilitate vector-matrix mathematics. MATLAB does not require the user to declare a variable as a scalar, vector, matrix, or an array. Scalar, vectors, and matrices have their conventional mathematical definitions, based on the number of elements and the number of rows and/or columns. Arrays resemble vectors and matrices, as both comprise elements in rows, columns, or both rows and columns. MATLAB distinguishes between matrices and arrays by the way one can operate on them. Matrix operators obey the rules of linear algebra. Array operators operate element by element.

The following assignment statement creates a vector or an array. Important: Note the use of square brackets!

figure ac

Note spaces separate the elements within brackets. Alternatively, the elements within brackets can be separated by commas, or by a mixture of commas and spaces.

figure ad

A semicolon terminates a row. Example:

figure ae

Is echoed to the screen as:

figure af

Individual elements can be addressed using row and column subscripts within parentheses. Example: The element, 7, is in the second row and third column of the matrix (or array), M4.

figure ag

The lowest index in MATLAB is 1, not 0!

MATLAB is very tolerant with vector-matrix mathematics. It will execute operations which are not defined in linear algebra, by interpreting your vectors and matrices as arrays. For example, in conventional vector-matrix mathematics, if b is a scalar, and B is a row vector, e.g.,

figure ah

and

figure ai

then the sum

figure aj

is not defined. MATLAB, however, will execute this statement and echo

figure ak

MATLAB has a type of array, called a “cell array,” to handle non-numerical data. It refers to the element of an array as a “cell.” The assignment statement for an array uses “braces” (which MATLAB refers to redundantly as “curly braces”). The assignment statement

figure al

is echoed as

figure am

Note the individual cell data are maintained. Contrast this result with a conventional array, defined by the use of square brackets, containing the same data. The assignment statement

figure an

is echoed as

figure ao

8.6.4 Operators

All programming languages provide at least three different types of operators: arithmetic, relational, and logical. Arithmetic operators are used in computations. Relational operators are used to define conditions to control the flow of a program’s execution. Logical operators are used for Boolean logic.

8.6.4.1 Arithmetic Operators

Operators and the symbols used for operators vary tremendously across programming languages. The only operators, whose meaning will not waver, are the arithmetic operators for multiplication, division, addition, subtraction, as long as they are used as “binary” operators (with two operands), as they were in elementary school. Many operators, other than dear Aunt Sally, are included in a programming language. The set of operators varies with the intended application of the language. For example, languages developed to program webpage applications will have operators to parse through strings of character data. MATLAB was written for scientific and engineering computation, so it has more mathematical operators than most languages.

Symbols to represent operations were limited to those on the computer keyboard. Consequently, operators are represented by combinations of symbols that made sense to the programmer, but do not follow any convention and vary widely between languages. For example, exponentiation of a to the b power, ab, is represented as a**b in FORTRAN, and a^b in MATLAB.

We will use these arithmetic operators in MATLAB: the elementary school arithmetic operators of multiplication, division, addition, subtraction; the “unary” plus and minus operators (which are simply the plus and minus signs); and exponentiation. The complete set of arithmetic operators is presented in Table A8.6.

This set requires some explanation. MATLAB uses the terms, “matrix operations” and “array operations,” to distinguish between conventional linear algebra operations performed with vectors and matrices from those operations not defined in linear algebra, which are performed with two arrays of the same size and shape, or on an array and a scalar.

Table A8.6 MATLAB’s arithmetic operators

An array operation is performed “element by element,” which means the operation is performed repeatedly, using elements in the same row and column position in each of the two arrays, until the operation has been performed on all the pairs. Note array operations are preceded with a dot (“.”), except for addition and subtraction, which are the same as matrix addition and subtraction, since they are performed element by element. For illustration, define two square arrays A and B:

$$A=\left( \begin{matrix} {{a}_{11}} & {{a}_{12}} \\ {{a}_{21}} & {{a}_{22}} \\\end{matrix} \right)\quad \text{and}\quad B=\left( \begin{matrix} {{b}_{11}} & {{b}_{12}} \\ {{b}_{21}} & {{b}_{22}} \\\end{matrix} \right)$$

Array Multiplication:

$$A.*B=\left( \begin{matrix} {{a}_{11}}{{b}_{11}} & {{a}_{12}}{{b}_{12}} \\ {{a}_{21}}{{b}_{21}} & {{a}_{22}}{{b}_{22}} \\\end{matrix} \right)$$

Array Right Division:

$$A./B = \left( {\begin{array}{*{20}{c}} {\frac{{{a_{11}}}}{{{b_{11}}}}}&{\frac{{{a_{12}}}}{{{b_{12}}}}} \\ {\frac{{{a_{21}}}}{{{b_{21}}}}}&{\frac{{{a_{22}}}}{{{b_{22}}}}} \end{array}} \right)$$

Array Left Division:

$$A.\backslash B = \left( {\begin{array}{*{20}{c}} {\frac{{{b_{11}}}}{{{a_{11}}}}}&{\frac{{{b_{12}}}}{{{a_{12}}}}} \\ {\frac{{{b_{21}}}}{{{a_{21}}}}}&{\frac{{{b_{22}}}}{{{a_{22}}}}}\end{array}} \right)$$

Array Power:

$$A.\hat{\ }B=\left( \begin{matrix} {{a}_{11}}^{{{b}_{11}}} & {{a}_{12}}^{{{b}_{12}}} \\ {{a}_{21}}^{{{b}_{21}}} & {{a}_{22}}^{{{b}_{22}}} \\\end{matrix} \right)$$

An exception to the syntax of preceding array operators with a dot is the transpose operator, “.’ ”. The transpose operator can operate on vectors, matrices, and arrays. It is a “unary” operator, since it has only one operand. The transpose operator interchanges the order of the elements to move an element from the rth row and cth column to the cth row and rth column. Example: If

$$C = \left( {\begin{array}{*{20}{c}} {\begin{array}{*{20}{c}} {{c_{11}}}&{{c_{12}}}&{{c_{12}}} \end{array}} \\ {\begin{array}{*{20}{c}} {{c_{21}}}&{{c_{22}}}&{{c_{22}}} \end{array}}\end{array}} \right)$$

then the C transpose is

$$C.' = \left( {\begin{array}{*{20}{c}} {\begin{array}{*{20}{c}} {{c_{11}}}&{{c_{21}}} \end{array}} \\ {\begin{array}{*{20}{c}} {{c_{12}}}&{{c_{22}}} \end{array}} \\ {\begin{array}{*{20}{c}} {{c_{12}}}&{{c_{22}}} \end{array}} \end{array}} \right)$$

MATLAB recognizes both i and j as imaginary numbers when a complex number is entered as

$$z=2+3i\quad \quad \quad \quad \quad \text{or}\quad \quad \quad \quad \quad z=2+3j$$

However, when MATLAB echoes back a complex number, i is used as the imaginary number.

The MATLAB operator, which transposes a complex number to obtain its complex conjugate, is “ “.

figure ap

The Colon operator, “:”, creates a range variable. Example: Type:

figure aq

and MATLAB will echo

figure ar

In this case, the variable, a, is now a vector or an array. The fifth element is

figure as

To increment by a value other than unity, indicate the first value of the series, the increment, and the upper limit. Example: The statement

figure at

yields two values: the initial value and one increment. The second increment would exceed the upper limit of the series

figure au

MATLAB includes two odd operators, Matrix Right Division and Matrix Left Division. Matrix division is NOT defined in linear algebra. The matrix “division” implemented in MATLAB is a shortcut for matrix inversion. Although matrix “division” may be advantageous in some circumstances, it is better to use matrix inversion.

Table A8.7 MATLAB’s array and matrix operators

8.6.4.2 Relational Operators

A computer language’s arithmetic operators are used for crunching numbers. The language’s relational operators are used to compare the values of variables. The operators allow a computer to “think,” by branching the flow of the execution on the outcome of relational expressions. Relational operators produce a result that is a Boolean, or “logical,” value, i.e., either true or false. For example, if A and B are numbers, then the answer to the question, “Is A greater than B?” must be either true or false.

MATLAB’s relational operators are given in Table A8.8.

Table A8.8 MATLAB’s relational operators

Only the last two operators require discussion. Note the relational operator, Equal, consists of two equal signs. A common error is to confuse the single equal sign, which is the assignment operator, and the double equal signs, which signify a relational equal operator. Also note the symbol for Not Equal, which is unusual. Most programming languages use the exclamation point, “!” for the “Not,” or logical inversion operator. Most engineers would read ~ = as approximately equal, which is why MATLAB chose it to represent Not Equal.

The distinction between approximately equal and equal is a warning for the use of the Equal operator in an if statement. The Equal relational operator requires an exact mathematical or logical equality, not an engineering equality. An engineer would accept the statement, 0.99999 = = 1, as true in most circumstances, but to MATLAB, the statement is false. Do not use the Equal relationship operator with floating point (scientific notation) variables, since they are likely to fail the comparison due to minute numerical error.

8.6.4.3 Logical Variables

Boolean logic is performed in MATLAB using “logical” variables which are defined or created by assigning them a logical value of either true or false. Note that true and false are lowercase. Numerical data can be converted to logical values with the function logical(). If the argument is positive, the result is true. If the argument is negative or zero, the result is false.

8.6.4.4 Logical Operators

MATLAB provides the three fundamental Boolean operations, And, Or, and Not in two forms, as operators and as functions.

Table A8.9 MATLAB’s logical operators

Boolean operators are used with relational operators to construct conditional statements that control which program instructions are executed. The Boolean operators are best described using “truth tables,” where A and B are Boolean variables which must have values of either \( true \equiv 1 \) or \( false \equiv 0. \)

Table A8.10 and truth table
Table A8.11 or truth table
Table A8.12 not truth table

8.6.5 Programming Statement Syntax

A computer programming language’s syntax is why computer code is called code. A programming language’s syntax is restrictive and specific, so that the characters read by the machine can be interpreted as instructions.

8.6.6 Assignment Statements

A program is a list of instructions coded in the programming language’s syntax. It is important to recognize that program statements are not equations. For example, the following assignment statement in the flowcharts Figs. A8.12 and A8.13 is a valid statement in all computer languages, even though it is not a valid equation, except in Boolean algebra

figure av

As an algebraic equation, this expression is nonsense. No number can be equal to itself plus one. As a program statement (or instruction), however, the expression not only makes sense, it is very important. It is the instruction to increment the value of the variable, n, by one. Recall this expression is called an assignment statement, and a variable name is an address in the computer’s memory. This assignment statement is understood by the computer as saying, “Write (or copy) the contents of the memory address(es) assigned to the variable, n, to the specialized hardware in the central processing unit called the accumulator, which performs operations on binary numbers. Add one to the value in the accumulator. Write the contents the accumulator to the memory address(es) assigned to the variable n.”

Assignment statements are read from right to left. The right side can be any valid mathematical statement expressed using MATLAB’s notation, with the restriction that variables cannot be used, before they have been assigned a value. If we use the expression, \( n = n + 1, \), before giving n an initial value (referred to as “initializing” the variable), a red error message would state

??? Undefined function or variable ‘n”’

The following code would execute properly

figure aw

Many languages require a character, such as a semicolon, to indicate the end of an instruction. MATLAB does not. In MATLAB, a semicolon at the end of a line prevents the code from being written to the monitor, when the program is executed. Echoing the code and the results to the monitor during execution of a program slows the execution considerably. Consequently, you will want to place semicolons at the end of line in loops which will execute repeatedly.

8.6.7 Control Flow Statements

8.6.7.1 If Statement

A fundamental instruction in all languages is an “if” statement. The syntax varies with the language but the essence is

if (expression A Relational Operator expression B) is true then execute the following instructions

In MATLAB, the syntax of an if statement is:

figure ax

The instructions appear between the conditional statement with the relational operator and the end statement. Important: MATLAB is case sensitive. The keywords, “if” and “end,” are both lower case. MATLAB highlights the leading “if” and the closing “end” in blue to demarcate the limits of the instructions, which will execute if the conditional statement is true. To further demarcate the if statement as a “block” of code, it is good practice to indent the instructions, which are executed by the if statement.

MATLAB and many other languages provide two additional instructions to supplement the if statement. They are “else” and “elseif.”

8.6.7.2 else Statement

The “else” instruction is used to divide the block of instructions between an if statement and its corresponding end statement into two blocks. The first block is executed, if the conditional statement is true. The second block is executed, if the conditional statement is false. Example:

figure ay

8.6.7.3 elseif Statement

The “elseif” instruction is a second conditional statement that follows an “if” statement. It is executed only when the conditional statement of the “if” statement is false. Example:

figure az

8.6.7.4 while Loop

A “while loop” uses a conditional statement to control the repeated execution of a block of code. The structure of a while loop resembles an if statement.

figure ba

The while loop differs from the if statement, in that the block of instructions of an if statement are executed only once, if the conditional statement is true. The block of code in a while statement is executed repeatedly, as long as the conditional statement remains true. It is possible to code an “infinite loop.” If you ever need to interrupt the execution of a MATLAB program, type CTRL + C simultaneously.

The following code with a while loop executes the computation flowcharted above.

figure bb

8.6.7.5 for Loop

A “for Loop” is a block of code which executes for a fixed number of times. The number of executions is controlled by a counter variable a range, using the colon operator. The block of code which executes repeatedly is demarcated with the key word, “end.” A MATLAB for loop has the following form:

figure bc

The following code would execute the computation flowcharted above

figure bd

“Nested” for loops are often used. The following code produces a matrix, or array, named A with two rows and three columns. The “inner” for loop increments through the columns. The “outer” for loop increments through the rows.

figure be

The result is

figure bf

8.6.7.6 Example: For Loop and While Loop

The following example is a first-order finite difference algorithm, programmed using a for loop to control the number of iterations through the loop:

figure bg

Here is an alternative program, using a while loop to control the number of iterations

figure bh

8.6.8 Comments

It is essential to include “comments” in a computer program to describe the algorithm and identify variables. Comments serve to document the program and make it easier to read. Comments must be distinguished from the program’s code. It seems every language uses a different symbol to identify a comment. MATLAB uses the percent sign, %. MATLAB will ignore all characters which follow a %. Comments may be included on the same line as a program instruction, or on a separate line. Example:

figure bi

Compare readability of the m-file code for the spring–mass–damper system above, with the m-file with comments below.

Commented script for the spring–mass–damper system state equations.

figure bj

8.6.9 plot Statement

The MATLAB command to create an x–y plot is

figure bk

where x and y are column vectors, or one-dimensional arrays of equal length. Multiple plots can be created using the same axes, by adding x, y pairs

figure bl

If you wish to plot two output variables, y1 and y2, against the same independent variable, t, then you must repeat the independent variable in each “x, y” pair

figure bm

8.6.9.1 Plotting and Labeling Multiple Figures

MATLAB plots onto a “graphic object” called a “figure.” In other words, a plot is the trace drawn on (or in) a figure. MATLAB’s function, plot (x, y), draws a plot of the x, y pairs of the vector x and the vector y on a figure. If a figure has not been created, then the function, plot (x, y), creates a figure. If a figure exists, then plot (x, y) wipes that figure clean, and draws a plot on it.

Plotting multiple figures requires creating a new figure with a number as its “handle” to identify it. The command is

figure bn

The following MATLAB code yields only the last plot of x3 vs. y3, because the figure created by the first plot would be reused twice.

figure bo

The command figure creates a graphic object. The following MATLAB code would yield three new plots numbered successively from 1, each time the code was run. Run the code four times, and a total of 12 plots would be created and stay open.

figure bp

There are two methods to limit the number of figures created by successive runs of the same code. One method is to use the close command, prior to the figure command. The command, close all, will close all open figures.

figure bq

The second method is to identify the figure with a “handle,” which, in our case, is a number. This is done by adding the figure number to the command, as an argument within parentheses. The following code creates the plot of x1 vs. y1 on figure number, 1. If figure number, 1, does not exist, the command, plot (x1,y1), creates it. If figure number 1 does exist, then the command, plot (x1,y1), will wipe it clean and reuse it.

figure br

8.6.9.2 Labeling Plots

If you are going to plot multiple figures, you must title them to identify them. A plot’s axes should be labeled to identify the variables and units.

Figure titles are added with the function title(‘Plot Title’). X-axis labels are added with the function, xlabel(‘meaningful x-axis label’). Y-axis labels are added with the command, ylabel(‘meaningful y-axis label’). The text used in these functions must be enclosed in single quotes. Example:

figure bs

8.6.9.3 Formatting Plots

There are various symbols, line types, and line colors available in MATLAB. They are selected by adding arguments to the plot(x, y) command after the pair of vectors. See Table A8.13. The default is a solid, black, thin (0.5) line. Formatting the line type, color, and width is particularly helpful when there are multiple plots (traces) on a figure. Line type formats are coded graphically; solid is ‘_’, dashed is ‘-’, dotted is ‘:’, and dot-dash is ‘–.’. Black is ‘k’, blue is ‘b’, red is ‘r’, and green is ‘g’. The following code draws plots of a dashed, blue line with a width of 2. Note the use of single quotes around ‘b’ and ‘LineWidth’.

figure bt

Color is assigned with a color letter code in single quotes. The colors are cyan, magenta, yellow, black, red, green, blue, and white. The line width is specified by ‘LineWidth’ in single quotes and without a space between the words, followed by a comma and a number indicating the width before the plot command. Examples:

figure bu

8.6.9.4 A Brief History of Control Characters

The syntax MATLAB uses to format data is a mixture of format strings from FORTRAN, a programming language which dominated engineering applications in the 1960’s and 1970’s, and control characters, which are a century older, dating from 1870’s International Telegraph Alphabet, the 5-bit code used to drive the first teletypes, invented by Emile Baudot. The unit baud, the SI unit for symbols per second, is named for Baudot.

The carriage return control characters, / r, refer to the carriage of a typewriter. The first teletypes were electromechanical typewriters. The carriage of a typewriter is the assembly, which carries the paper; the “platen,” a rubber-covered roller which backed up the paper; the feed rollers; and guides. The carriage moved the paper from right to left in front of the key bars. The linkages connected the key of the keyboard with the type slug, which struck the ink-saturated cloth ribbon, and transferred the image of a character to the paper. Teletypes were used for a century and evolved significantly over that period. The last teletype model found a market as an input/output device with the old “main frames” and “minicomputers.” Teletypes were used in place of computer monitors, because the teletypes were less expensive, even though they cost approximately $700 in 1970. To put that in perspective, a Volkswagen cost less than $2,000 in 1970. Teletypes died out, when the introduction of inexpensive dot matrix printers finally made them obsolete in the late 1970s. You will never work with one, but you will see them in movie scenes of newspaper newsrooms from the twentieth century. (Soon, you will only see newspapers in movies too.)

Table A8.13 MATLAB’s line type, color, and marker format codes

8.6.10 Programming a Function in MATLAB

See Sect. 8.3 of this chapter.

8.6.11 Reading From and Writing To Files

We will need to read data from files and write data to files, in order to use MATLAB with laboratory data. MATLAB conveniently has interactive methods using a graphical user interface. However, our present focus is on programming. Because Microsoft’s Excel is so widely available, it is common for engineering software, including MATLAB and Mathcad, to be able to read and write numerical data to and from an Excel worksheet. MATLAB also includes more general and flexible functions for reading and writing data to files, which we would need to use for reading and writing strings of characters or data to a “text.” Unfortunately, complex syntax is the price of flexibility. The programmer is responsible for “opening” and “closing” files and “formatting” the data. The latter is a throwback to the days of programming computers using punch cards. We will stick with Excel worksheets.

In order to use MATLAB’s syntax to read and write Microsoft Excel files, we need to either assemble an array to write to an Excel worksheet or disassemble an array read from an Excel worksheet.

8.6.11.1 Concatenation of Arrays

“Concatenation” is the operation of joining arrays to create a new array. It is easiest to understand the operation through illustration. Starting with arrays A and B, where

$$A=\begin{matrix} {{a}_{11}} & {{a}_{12}} \\ {{a}_{21}} & {{a}_{22}} \\\end{matrix}\,\,\,\,\,\,\,\,\,\,\text{and}\,\,\,\,\,\,\,\,\,\,\,B=\begin{matrix} {{b}_{11}} & {{b}_{12}} \\ {{b}_{21}} & {{b}_{22}} \\\end{matrix}$$

Arrays A and B can be concatenated as either

$$C = \begin{array}{*{20}{c}} {{a_{11}}}&{{a_{12}}}\\ {{a_{21}}}&{{a_{22}}}\\ {{b_{11}}}&{{b_{12}}}\\ {{b_{21}}}&{{b_{22}}} \end{array}\,\,\,\;or\;\;\;\,D = \begin{array}{*{20}{c}} {{a_{11}}}&{{a_{12}}}&{{b_{11}}}&{{b_{12}}}\\ {{a_{21}}}&{{a_{22}}}&{{b_{21}}}&{{b_{22}}} \end{array}$$

MATLAB’s concatenation function, cat \(( {\alpha ,\beta ,\gamma } ), \) takes three arguments. The first argument, α, controls whether arrays β and γ are concatenated with β above and γ below, or side-by-side with β to the left and γ to the right. The argument, α, is the “dimension” along which the concatenation occurs. We will most often work with one or two-dimensional arrays. A one-dimensional array has only rows, x row . Therefore, the dimension of the element index for rows is 1. A two-dimensional array has rows and columns, y row,column . The dimension of the index for columns is two. The MATLAB syntax which produced arrays C and D is

$$C=cat\left( 1,A,B \right)\,\,\,\,\,\,\,\,\,\,\text{and}\,\,\,\,\,\,\,\,\,\,\,D=cat\left( 2,A,B \right)$$

If you prefer not to work with the dimensions, MATLAB also provides the functions, vertcat() and horzcat()

$$C=vertcat\left( A,B \right)\,\,\,\,\,\,\,\,\,\,and\,\,\,\,\,\,\,\,\,\,\,D=horzcat\left( A,B \right)$$

The most common error in concatenating arrays is to attempt to concatenate two-dimensional arrays which do not “fit” next to each other properly. Two arrays must have the same number of columns if they are to be concatenated above and below, or the same number of rows if they are to be concatenated side by side.

By the way, when MATLAB help refers to “multidimensional arrays,” it means arrays with more than two dimensions.

8.6.11.2 Extracting a Row or Column from a Two-Dimensional Array

MATLAB uses the colon operator “:” as shorthand for a range variable which indexes by unity. The lower limit, j, and the upper limit, k, can be assigned as j:k.

When a range variable is used as one of the indexes of an array, and no limits are assigned to the range variable, in other words, the colon is used by itself, then the range variable is assigned the limits of the row or column of the array. This shorthand notation makes it simple to extract a single column or row from an array. For example, the following code extracts the second column from the array C and assigns it to the variable, data2:

data2 = C(:,2)

yielding the column vector

$$data2=\begin{matrix} {{a}_{12}} \\ {{a}_{22}} \\ {{b}_{12}} \\ {{b}_{22}} \\\end{matrix}$$

We achieve the same result using the lower limit of one and the upper limit of four

figure bv

8.6.11.3 Reading and Writing to a Microsoft Excel Worksheet File

The MATLAB syntax for reading a Microsoft Excel worksheet file and assigning the data to the variable, data3, is

figure bw

Note the name of the file to be read is the complete file path, enclosed in single quotes. If you do not see the file path in the colored “address bar” at the top of the dialog, use the “Tools” menu to change the file settings. The complete file path will have a form similar to

figure bx

It is easier to read from or write to a flash drive, which will have a short full path name. If your flash drive were assigned the drive letter R, then the full path name would be

figure by

The syntax for creating Excel worksheet file and writing to it is

figure bz

where “array to be written” is the variable name of the array.

Example: Say you plot the result of a Runge–Kutta simulation, and wish to save it as a Microsoft Excel worksheet file. The plot() function requires vectors holding the x data, time in our case, and y data, say force F. We will concatenate these data into a two-dimensional array, name the array, plot_output, and write the data as an Excel worksheet file to a flash drive R with the following code.

figure ca

8.6.11.4 Reading and Writing to a “Text” File

Although we refer to many different “types” of files, such as a Microsoft “doc” file, a Mathcad “mcd” file, a MATLAB “m” file, etc., what we are referring to are the filename “extensions” (what follows the final dot in the file name), which allow a program to recognize a family of files it can read and write to. There are, in fact, only two fundamental file types binary files, in which data are encoded in binary and text files, in which data are encoded in characters. Most of the files created by the programs we work with are text files.

When you read or write to an Excel file in MATLAB, you gain the convenience of letting MATLAB handle many of the required details for you, but you sacrifice your independence, in that you do things the way MATLAB wants you to. Reading and writing text files in MATLAB is more involved than Excel files. You regain your freedom, and the responsibility that comes with it, to take care of the details.

There are three steps for writing to or reading from a text file.

  1. 1.

    “Open” the file, meaning

    1. a.

      identify or create a file

    2. b.

      declare whether you plan to write to it or read from it

    3. c.

      assign the file to a variable name

  2. 2.

    Write (or read) line by line using a loop

    1. a.

      “format” the data by defining the width of the “field” and the data type

    2. b.

      end the line of data with a carriage return or new line “control character”

  3. 3.

    “Close” the file

The command to open a file is

figure cb

Note the use of SINGLE quotes around the “file_name” and the argument “w,” where “w” means the file is opened to write to. Example:

figure cc

The command to write a line of two formatted data to an open file is

figure cd

The command fprintf() stands for File Print Formatted.

The syntax MATLAB uses to format data is literally from the 1960’s. All of the formatting information is between two single quotes. A format “string” begins with a percent sign, %, to indicate what follows is the format code. There must be as many format strings as there are data. The first format string formats the first datum. The second format string formats the second datum. Note there are no commas between format strings, just a space, while the data variables are separated by commas.

Fig. A8.13
figure 51

fprintf function, annotated to show the association of format strings and data

An example is

figure ce

The first number following the percent sign is the maximum number of numbers to be written. This is the “field width.” It will be padded with blanks to the left of the most significant digit. Next, there is a decimal point followed by a number. The number after the decimal point, called the “precision,” is the number of digits to be written after the decimal point. The format string ends with a letter called a “conversion character,” which specifies the notation the number is to written in. We will use either f to mean “fixed” format, which is a conventional decimal number, or e to mean “exponential,” or scientific notation. Note that f must be lower case, but either e or E is acceptable. Example: The number, 31,415.92, converted using both fixed and exponential format strings:

figure cf

A common error is to use too narrow a field width. Remember that the field width includes the spaces between the data also, unless those are added as a text string, or with a\t, for tab, which are control characters.

The formatting information ends with “control characters” which date from the 1930s and teletypes. Two useful control characters, when written to a file, are\n, which commands a “new line” and\r, which commands a “carriage return.”

Closing the file is the easy part. The command is

figure cg

Forgetting to close a file means it cannot be opened and read. If you can access the file you created, check to see if you closed the file in your code.

The following is MATLAB code which writes the arrays, rkt and rkx1, to the file, Lab3_RK_Lin_09172014.txt.

figure ch

8.6.12 MATLAB’s step() and impulse() Functions

MATLAB’s Control System Toolbox contains the functions, step() and impulse(), which calculate the unit step response and the unit impulse response of a transfer function. The ability to calculate a time-domain response from a transfer function is a tremendous convenience. The step() and impulse() functions take the same arguments and work the same way. The following discusses the function step() but also applies to impulse(). If step() is given the name of a transfer function, say Model, as its single argument, step(Model), the duration of the response may or may not meet our needs. We can set an end time for the calculation, by adding a scalar argument, say \( tend = 0.5, \) step(Model, tend), to force unit step calculation to run from \( t = 0 \) to \( t = tend. \) We can also pass step() a vector with the times at which to evaluate the unit step response. In our application, the time vector would be that of the observed response, step(Model, timeVector).

The following MATLAB m-file program reads the RCL circuit discharge data used in the Mathcad code above from Excel files, plots the data, then calculates and plots the impulse response of the model.

figure ci
figure cj
figure ck

8.6.13 Vector Calculations in MATLAB

MATLAB has two functions to determine the number of elements in a vector, length(), used on vectors, and size(),which is used on arrays of any number of dimensions, including vectors. When size() is used on a vector, it will return the number of rows, n, and the number of columns, 1, as a row vector, [n 1]. Remember that a space or a comma can be used to separate elements in a row in MATLAB. Rows of vectors and arrays are separated by semicolons.

Calculation of the integrals of the error, the absolute value of the error, and square of the error is performed in MATLAB with for end loop. The MATLAB m-file program follows:

figure cl
figure cm
figure cn
figure co
Fig. A8.14
figure 52

Plot created by Program Lab 0 RLC Discharge Data and Model

Rights and permissions

Reprints and permissions

Copyright information

© 2014 Springer Science+Business Media New York

About this chapter

Cite this chapter

Seeler, K. (2014). Finite Difference Methods and MATLAB. In: System Dynamics. Springer, New York, NY. https://doi.org/10.1007/978-1-4614-9152-1_8

Download citation

  • DOI: https://doi.org/10.1007/978-1-4614-9152-1_8

  • Published:

  • Publisher Name: Springer, New York, NY

  • Print ISBN: 978-1-4614-9151-4

  • Online ISBN: 978-1-4614-9152-1

  • eBook Packages: EngineeringEngineering (R0)

Publish with us

Policies and ethics