BRWN FR

10.

11,

. Acknowledgements . Preface

. Study Guide

. Introduction

1. What is MATLAB? 2. Problem Set

. Getting Started

1. Essentials 2. Problem Set

. Graphics

1. Plotting in MATLAB 2. Problem Set

. Introductory Programming

1. Writing Scripts to Solve Problems 2. Problem Set

. Interpolation

1. Interpolation 2. Problem Set

. Numerical Integration

1. Computing the Area Under a Curve 2. Problem Set

Regression Analysis 1. Regression Analysis 2. Problem Set

Publishing with MATLAB 1. Generating Reports with MATLAB 2. Problem Set

Acknowledgements

I would like to express my appreciation to all of my students in the Power and Process Engineering program between the academic years 2011-12 and 2015-16 for their feedback and understanding that this book is a work in- progress.

Special thanks go to those who supported the book along the way:

Dr. David Porter[footnote], the founder of BCIT OER Group in 2015 who constantly provides me with the latent energy to continue working on this book,

Mr. Alex Podut with whom I co-taught MATLAB in 2015. His input was very valuable,

Dr. Sanja Boskovic who promoted this book at management levels in 2012,

Mr. Sergiy Yatlo who gave feedback to the first iterations of the book in early 2011.

Preface Preface to "A Brief Introduction to Engineering Computation with MATLAB"

In my tenth year at the Institute, I dedicate this book to the BCIT community.

The primary purpose of writing a book and distributing it free-of-charge is to extend my gratitude to BCIT. I am particularly thrilled to do it with this textbook because it is a product of many learning opportunities BCIT has offered me over a period of several years. What follows is a brief background on how this book came to be.

My post-secondary teaching career began on 22 January 2001 at the Pacific Marine Training Campus of BCIT when I logged on to a Unix workstation to instruct in the Propulsion Plant Simulator. That has been a major milestone in many ways in my professional life. While learning inner workings of Unix operating system (OS), I also made a discovery and that discovery profoundly changed my view on how I thought the world operated. The discovery was the GNU/Linux OS and open source software (OSS) movement through several books, most notably Just for Fun: The Story of an Accidental Revolutionary[footnote] and The Cathedral and the Bazaar[footnote]. I was convinced that the collective power of connected individuals around the world and the global infrastructure of the Internet had the potential to change the ways the world functioned.

Just for Fun: The Story of an Accidental Revolutionary by L. Torvalds and D. Diamond, New York: HarperCollins Publishers. © 2001

The Cathedral and the Bazaar by E. S. Raymond, Sebastopol: O’Reilly Media. © 1999

In the last 10 years, BCIT has allowed me to study various subjects through its Professional Development (PD) programs for which I am very grateful. I learned a great deal in PD courses and in one of the recent ones, I had two déja vu moments similar to my discovery of OSS movement. The first one occurred when I began reading The Wealth of Networks|[footnote] and the second one when I found about Connexions. The former was a confirmation of my 10-year old discovery and the latter is what I am using to write this book. Connexions is a web-based curricular content authoring and

publishing technology that I believe has a growing potential for writing and distributing free-of-charge learning materials.

The Wealth of Networks by Y. Benkler, New Haven: Yale University Press. © 2006

Thus, motivation for this book stems from the notions that were generated by the OSS movement. The book was written to pay a small token of appreciation to BCIT and I hope it will be a contribution to the open educational resources repository.

Serhat Beyenir North Vancouver, B. C. 25 October 2011

Study Guide Study guide for learners.

MATLAB, a sub-course of Computer Technology 1 and this text are specifically designed for students with no programming experience. However, students are expected to be proficient in First Year Mathematics and Sciences and access to good reference books are highly recommended. I also assume that students have a working knowledge of the Mac OS X or Microsoft Windows operating systems.

The strategic goal of the course and book is to provide learners with an appreciation for the role computation plays in solving engineering problems. The MATLAB specific skills that I would like students to acquire are as follows:

e Write scripts to solve engineering problems including interpolation, numerical integration and regression analysis,

e Plot graphs to visualize, analyze and present numerical data,

e Publish reports.

The best way to learn about engineering computation is to actually do it. We will therefore solve many engineering problems mainly using a recent version of MATLAB in this book. Since the primary focus is engineering computation, we will concentrate on the mathematical solutions and, to a limited extent, the graphical user interface (GUI) features of MATLAB.

Learning a new skill, especially a computer program, can be an overwhelming experience. To make the best of this process, students are encouraged to observe the following guidelines that have proven to work well:

e Plan to study 2 hours outside of class for every hour inside of class,

e Practice, practice, practice: As the old saying goes, practice makes one perfect or perhaps we should modify that statement: Good practice makes one perfect,

e Buddy system: Study with a classmate. Helping one another drastically improves your understanding of the material. Particularly, students are advised to work the problem sets in this fashion,

e Muddy points: Make a note of muddy points as they may occur during lectures and email your notes to me. I will address those issues at the beginning of the next class,

e Open book exam: Do not try to memorize commands, functions or their syntax but learn where and how to find that information. Through many exercises and problem sets you will have solved by the end of the course, most computational routines will become second nature to you. The exam is open book, so keep your learning materials and m- files well organized.

What is MATLAB? A brief introduction to MATLAB.

Why MATLAB GUI he Ip

www, hetemeal.com

MATLAB stands for MATrix LABoratory (see wikipedia) and is a commercial software application written by The MathWorks, Inc. When you first use MATLAB, you can think of it as a glorified calculator allowing you to perform engineering calculations and plot data. However, MATLAB is more than an advanced scientific calculator, for example MATLAB's sophisticated numerical computation environment also allows us to analyze data, simulate engineering systems, document and share our code with others.

Why Use MATLAB?

MATLAB has become a defacto standard in many fields of engineering and science. Even a casual exploration of MATLAB should unveil its computational power however a closer look at MATLAB's graphics and data analysis tools as well as interaction with other applications and programing languages prove why MATLAB is a very strong application for technical computing.

The standard MATLAB installation includes graphics features to visualize engineering and scientific data in 2-D and 3-D plots. We can interactivity build graphs and generate MATLAB command output that can be saved for use in the future. The saved-instructions can be called again with different data set to build new plots. The plots created with MATLAB can be exported in various file formats (e.g. .jpg, .png) to embed in Microsoft Word documents or PowerPoint slideshows.

MATLAB also contains interactive tools to explore and analyze data. For example, we can visualize data with one of the many plotting routines, zoom in to plots to take measurements, perform statistical calculations, fit curves to data and evaluate the obtained expression for a desired value.

MATLAB interacts with other applications (e.g. Microsoft Excel) and can be called from C code, C++ or Fortran programming language.

Running MATLAB

To use MATLAB, it must be installed on your computer and you can start it just like you start any application on your system or you must have access to a network where it is available.

BCIT holds a Total Student Headcount (TSH) license for Mathworks software and this allows students to install MathWorks software on their personally-owned computers.

Matlab download and installation instructions for BCIT students

For your install, choose the latest version available and install MATLAB, Curve Fitting Toolbox and Symbolic Math Toolbox.

In addition, MATLAB Online provides access to MATLAB from your web browser. Just log in to use MATLAB:

Access MATLAB From Your Web Browser

The MATLAB Desktop

When you start the MATLAB program, it displays the MATLAB desktop. The desktop is a set of tools (graphical user interfaces or GUIs) for managing files, variables, and applications associated with MATLAB. The first time you start MATLAB, the desktop appears with the default layout, as shown in the following illustration.

Command Window fe >> cid| J) SRECYCLE.BIN J) Temporaryltems J» 2008 builds ) Desktop 4 Documents LabVIEW Data MATLAB .) MyCourses }) PersonalFiles » public_html! CommandHistoy ss © J slprj $-- 03/10/2014 12:02 --% A temn

Select a file to view details

The MATLAB Desktop.

Command Window

The Command Window is where we execute MATLAB commands. We enter statements at the Command Window prompt. The prompt can be any

one of the following:

e Trial>> indicates that the Command Window is in normal mode and the MATLAB license will expire after the trial period ends.

e EDU>> indicates that the Command Window is in normal mode, in MATLAB Student Version.

e >> indicates that the Command Window is in normal mode.

Command Window

The Command Window.

Command History

The Command History is a log of the commands we have executed in the command window.

The Command History.

Workspace

The workspace consists of a set of variables stored in memory during a MATLAB session. To open the Workspace browser, select Desktop > Workspace in the MATLAB desktop, or type

>> workspace

at the Command Window prompt.

Current Folder

The Current Folder is like the Finder in Mac OS X or Windows Explorer in Windows operating systems and allows us to browse through the files and folders. The Current Folder also displays details about files in your current directory and within the hierarchy of the folders it contains.

@o> 8 Wau: +p

Current Folder.

) PersonalFiles public_html » slprj J) temp ) untitled_grt_rtw J) UserProfile J userprofiler2

Current Folder docked on the desktop.

Tool Strip

The tool strip contains global tabs, Home, Plots and Apps. Contextual tabs become available when you need them.

[aoe

Tabs.

The plots tab allows us to plot various types of graphs quickly and easily.

Q)| Search Documentation SiS » ot |) || ur

y

°

The plots tab.

The apps tab.

Layout button allows us to change the desktop layout or go back to the default configuration.

Toolbar

The MATLAB toolbar provides on-screen buttons to access frequently used features such as, copy, paste, undo and redo.

Keyboard shortcuts

MATLAB provides keyboard shortcuts for viewing a history of commands and listing contextual help.

1. The up arrow key, 2. The tab key, 3. The semicolon symbol.

The Up Arrow Key

Suppose we want to enter the following equation: >> y=sin(45)

But we mistakenly entered

>> y=sine(45)

MATLAB returns the following prompt:

22? Undefined function or method ‘'sine' for input arguments of type 'double'.

Instead of retyping the equation, press the up arrow key, the mistakenly entered line is displayed. Using the left arrow key, move the cursor to the misspelled letter. Make the correction and press Return or Enter to execute the command.

Pressing the up arrow key repeatedly recalls the previously entered commands. Likewise, typing the first characters of previously entered line and pressing the up arrow key displays the full command line. To execute that line, simply press the Return or Enter key.

The Tab Key

Suppose you forgot how to enter the square root command. Begin typing Y=sq in the command prompt:

>> y=sq

Then press the tab key and scroll down to sqrt. Select it and press Return or Enter key.

>> y=sqrt

The Semicolon Symbol

The semicolon symbol at the end of a line suppresses the screen output. This is useful when you want to keep your command window clean.

Type the following entry and press the Return key: >> y=2+2 The following output is displayed: v= 4 Now, press the up arrow key to recall our initial entry >> y=2+2 And insert a semicolon as follows: >> y=24+2; No numerical result is displayed however MATLAB stores the value of y in

the memory. We can recall the value y by simply typing y and pressing Return.

MATLAB Help

MATLAB comes with three forms of online help: help, doc and demos.

Help

Typing help in the Command Window lists all primary help topics. You can display a topic by clicking on the link.

>> help

ERE

|/2 4. Chp2_Exercise9 |= Chp3_Exercisea \]2 L. EngineeringComputati... J figs & } html ) M-Files_HeatTransfer » siprj J ..DS_Store |_| .DS_Store © AcetyleneBottle.m © AcetyleneBottlelnterac... ©) AcetyleneBottlelnterac... hb Chn? Fxercise9.7in Chp3_Exercise4 (Folder)

v

v

No details available

Bi

>> help HELP topics:

Nn) 6.75

matlab\testframework

matlab\demos Matlab\graph2d matlab\graph3d Matlab\graphics matilab\plottools Matlab\scribe Matlab\specgraph Matlab\uitools toolbox\local matlab\optimfun Matlab\codetools matlab\datafun Matlab\datamanager Matlab\datatypes matlab\elfun matlab\elmat matilab\funfun matlab\general matlab\gquide matilab\helptools matlab\iofun

marlah\lanc

(No table of contents file)

(No table of contents file) Examples.

Two dimensional graphs.

Three dimensional graphs.

Handle Graphics.

Graphical plot editing tools Annotation and Plot Editing. Specialized graphs.

Graphical user interface compone General preferences and configuz Optimization and root finding. Commands for creating and debuge Data analysis and Fourier tranat (No table of contents file)

Data types and structures. Elementary math functions. Elementary matrices and matrix n Function functions and ODE solve General purpose commands. Graphical user interface design Help commands.

File input and output.

Procramming landace constructs

[1,2,3,4,5,6,7,8, [0.5403,-0.4161,-

Command History ‘cic

help

help cle help clic help clc help

Help.

Or if you know the command or function you need help with, you can type help followed by the command or function. For example to learn about c1c command, type help clc at the command prompt:

>> help clc

>> help cic elc Clear command window. r 11,2,3,4,5,6,7.8 ele clears the command window and homes the cursor. [0.5403,-0.4161,-

See also home.

Reference page in Help browser

doc cl _) M-Files_HeatTransfer mene

Db siprj

) _.DS_Store

1 .DS_Store

©) AcetyleneBottle.m

1) AcetyleneBottlelnterac...

3) AcetyleneBottlelnterac...

Ub Cho? Fxercise9.7in | y=cos (x) Chp3_Exercise4 (Folder) plot (y)

help

No details available

help clic

help clic

The output of >> help clc command.

Also try the following command: >> help clear

Se i > Hu: > MAT

>> help clear 2B Chp2_Exercise9 clear Clear variables eis functions from memory. r] [1,2,3,4,5,6,7,8,9,, clear removes all variables from the workspace. a mY Chp3_Exercise4 clear VARIABLES does the same thing. (0.5403,-0.4161,- » EngineeringComputati... clear GLOBAL removes all global variables. & figs clear FUNCTIONS removes all compiled MATLAB and MEX-functions

J htm ) M-Files_HeatTransfer » slprj () DS Store clear IMPORT clears the base import list. It can only be iss ia DS Store command prompt. It cannot be used in a function.

meee clear CLASSES is the same as clear ALL except that class defi © AcetyleneBottlelnterac... are also cleared. If any objects exist outside the workspace Command History © AcetyleneBottlelnterac... userdata or persistent in a locked program file) a warning wi Ee 1) Chn? FExercise9.7in issued and the class definition will not be cleared. clear Ci Chp3_Exercised (Folder) be used if the number or names of fields in a class are chanc

clear ALL removes all variables, globals, functions and MEX 1] clear ALL at the command prompt also clears the base import 1

doc demos clc clear JAVA is the same as clear ALL except that java classes help dynamic java path (defined using JAVACLASSPATH) are also cle cle help cic clear VAR1 VAR2 ... clears the variables specified. The wilde help character '*"' can be used to clear variables that match a pat instance, clear X* clears all the variables in the current we that start with X.

No details available cle

help clc

help clear

The output of >> help clear command.

To learn about sine function, type help sin at the command prompt:

>> help sin

Doc

Obviously, to use he 1p effectively, you need to know what you are looking for. Often times, especially when you first start learning an application, it is usually difficult to ask the right questions. In the case of MATLAB, doc command is generally better than he Lp. If you type doc in the command prompt, MATLAB opens a browser from where you can obtain help easier:

>> doc

@ Help

@% 3 - G7 | Home | +

Search Documentation

Installation Release Notes

MATLAB

Simulink

Control System Toolbox Data Acquisition Toolbox DSP System Toolbox Embedded Coder

Image Processing Toolbox Instrument Control Toolbox MATLAB Coder

MATLAB Report Generator Optimization Toolbox Real-Time Windows Target Signal Processing Toolbox

SimDriveline

SimEvents

SimHydraulics SimMechanics SimPowerSystems Simscape

Simulink 3D Animation Simulink Coder

Simulink Control Design Simulink Design Optimization Simulink Real-Time

Simulink Report Generator Stateflow

Symbolic Math Toolbox System Identification Toolbox

Built-in MATLAB Documentation.

Like using help sin, try typing doc sin in the command prompt:

>> doc sin

Demos

You can learn more about MATLAB through demos by typing demo in the command prompt, a list of links to demos will open in Help Browser. Demos and online seminars are available at product demos and online

seminars.

>> demo

» 3 xk- MATLAB Examples x| +] Bo elo) ~ Contents z Search Documentation pe] Documentation Center e MATLAB v MATLAB

> Getting Started with MATLAB MATLAB Examples Release Notes : Functions On this page...

> Language Fundamentals > Mathematics

> Graphics | Language Fundamentals > Programming Scripts and Functions | Mathematics

> Data and File Management | Graphics

> GUI Building

Programming > Advanced Software Development eae | Data Import and Expo

Creating Graphical User Interfaces | Other Examples

| New Features Videos

Getting Started More Examples

em Getting Started with MATLAB (5 min, 6 sec) EB Video

SS Working in The Development Environment (5 min, 21 sec) EB Video

Language Fundamentals

Create a Structure Array @ Script

Built-in MATLAB Demos.

Useful Commands and Functions

For a detailed explanation and examples for each of the following type ‘help function’ (without quotes) at the MATLAB prompt.

Command/Function cle

clear

who, whos workspace

cd

pwd

computer

ver

quit

exit

Summary of Key Points

Meaning

Clear Command Window Remove items from workspace List variables in workspace Display Workspace browser Change working directory Display current directory

Identify information about computer on which MATLAB is running

Display version information for MathWorks products

Terminate MATLAB

Terminate MATLAB (same as quit)

Useful commands and functions

1. MATLAB is a popular technical computing application and MathWorks offers a trial version of MATLAB on their website,

2. The MATLAB Desktop consists of Command Window, Command History, Workspace, Current Folder and Start Button,

3. The up/down arrow keys, the tab key and the semicolon are convenient tools to use the Command Window,

4. MATLAB features an online help, doc and demo,

5. Various commands and functions make MATLAB experience easier, forexample,clc, clear and exit.

Problem Set Problem Set for What is MATLAB? Exercise:

Problem: Learn about the following terms using he 1p command:

1. workspace 2. plot

3. clear

4. format

9. roots

Solution:

1.>> help workspace WORKSPACE Open Workspace browser to manage workspace WORKSPACE Opens the Workspace browser with a view of the variables in the current Workspace. Displayed variables may be viewed, manipulated, saved, and cleared. See also whos, openvar, save. Reference page in Help browser doc workspace >>

2.22 help plot PLOT Linear plot. PLOT(X,Y) plots vector Y versus vector X. If X or Y is a matrix, then the vector is plotted versus the rows or columns of the matrix, whichever Tine Ups ii x, 1s) a) scalar and ¥ 1S a Vector, disconnected line objects are created and plotted as discrete points vertically at X.

3.>> help clear CLEAR Clear variables and functions from memory. CLEAR removes all variables from the workspace. CLEAR VARIABLES does the same thing. CLEAR GLOBAL removes all global variables. CLEAR

FUNCTIONS removes all compiled M- and MEX- functions. CLEAR ALL removes all variables, globals, functions and MEX links. CLEAR ALL at the command prompt also removes the Java packages AMPOre PiSt tava. toon

.>> help format FORMAT Set output format. FORMAT with no inputs sets the output format to the default appropriate for the class of the variable. For float variables, the default aS FORMAT SHORT: .: 2...

.>> help roots ROOTS Find polynomial roots. ROOTS(C) computes the roots of the polynomial whose coefficients are the elements of the vector C. If C has N+1 components, the polynomial is C(1)*X‘N +

fe (CN) 2 Xe ONG Ih) Sees care

Essentials Essential skills to use MATLAB effectively.

Pol yromals

www, hetemeal.com

Learning a new skill, especially a computer program in this case, can be overwhelming. However, if we build on what we already know, the process can be handled rather effectively. In the preceding chapter we learned about MATLAB Graphical User Interface (GUI) and how to get help. Knowing the GUI, we will use basic math skills in MATLAB to solve linear equations and find roots of polynomials in this chapter.

Basic Computation

Mathematical Operators

The evaluation of expressions is accomplished with arithmetic operators as we use them in scientific calculators. Note the addtional operators shown in the table below:

Operator

+

Operators

Name

Plus

Minus

Asterisk

Forward Slash

Back Slash

Caret

Dot Asterisk

Dot Slash

Dot Back Slash

Dot Caret

Description Addition Subtraction Multiplication Division

Left Matrix Division Power

Array multiplication (element- wise)

Right array divide (element-wise)

Left array divide (element-wise)

Array power (element-wise)

Note:The backslash operator is used to solve linear systems of equations,

see [link].

Note: Matrix is a rectangular array of numbers and formed by rows and

i 2 et 5 6 7 8 columns. For example A = . In this example A 9 10 11 12 13 14 15 16

consists of 4 rows and 4 columns and therefore is a 4x4 matrix. (see Wikipedia).

Note:Row vector is a special matrix that contains only one row. In other words, a row vector is a 1xn matrix where n is the number of elements in the row vector. B= (1 2 3 4 5)

Note:Column vector is also a special matrix. As the term implies, it contains only one column. A column vector is an nx1 matrix where n is the 1

number of elements in the column vector. C =

ao ® Ww bh

Note:Array operations refer to element-wise calculations on the arrays, for example if x is an a by b matrix and y is ac by d matrix then x.*y can be

performed only if a=c and b=d. Consider the following example, x consists of 2 rows and 3 columns and therefore it is a 2x3 matrix. Likewise, y has 2

12-3 rows and 3 columns and an array operation is possible. x = ( )

4 5 6

10 20 30 10 40 90

and y = then x.*y = 40 50 60 160 250 360

Example:

The following figure illustrates a typical calculation in the Command

Window.

Current Folder

} SRECYCLE.BIN ) Temporaryltems » 2008 D builds

.) Custom Office Templates ) Desktop ). Documents ) LabVIEW Data MATLAB ) MyCourses

). PersonalFiles

a’ a SP? EAs H>

Command Window >> 242

>> 40/5

ans =

>>-2"3

Operator Precedence

|_|

Command History ©

x=12 4|

y=55

z=x+y

buried_duct

Problem2014 2

1 2x 10

cle

2+2

5*8

40/5

2*3

%-- 03/06/2015 09:20 --%

MATLAB allows us to build mathematical expressions with any combination of arithmetic operators. The order of operations are set by precedence levels in which MATLAB evaluates an expression from left to right. The precedence rules for MATLAB operators are shown in the list

below from the highest precedence level to the lowest.

1. Parentheses ()

2. Power (‘)

3. Multiplication (*), right division (/), left division (\) 4. Addition (+), subtraction (-)

Mathematical Functions

MATLAB has all of the usual mathematical functions found on a scientific calculator including square root, logarithm, and sine.

Note: Typing

pi

returns the number 3.1416. To find the sine of pi, type in sin(p1)

and press enter.

Note:The arguments in trigonometric functions are in radians. Multiply degrees by pi/180 to get radians. For example, to calculate sin(90), type in

sin(90*pi/180)

Note:In MATLAB

log

returns the natural logarithm of the value. To find the In of 10, type in log(10) and press enter, (ans = 2.3026).

Note:MATLAB accepts log10

for common (base 10) logarithm. To find the log of 10, type in log10(10) and press enter, (ans = 1).

Practice the following examples to familiarize yourself with the common mathematical functions. Be sure to read the relevant he 1p and doc pages for functions that are not self explanatory.

Example: Calculate the following quantities: 93 iP 32-1? 50 oF =? for d=2

MATLAB inputs and outputs are as follows:

aks —— is entered by typing 243/( 342-1) (ans = 1) 2. 59-5 — J is entered by typing sqrt (5) -1 (ans = 1.2361)

3. <a for d=2 is entered by typing pi/4* 2/2 (ans = 3.1416)

Example: Calculate the following exponential and logarithmic quantities:

ie 2; In(5"°) 3. log 10°

MATLAB inputs and outputs are as follows:

1.exp(2) (ans = 7.3891) 2. log( (5410) ) (ans = 16.0944) 3. 1log10(1045) (ans =5)

Example: Calculate the following trigonometric quantities:

1. cos(Z) 2. tan(45) 3. sin(7) + cos(45)

MATLAB inputs and outputs are as follows:

1. coSs(pi/6 ) (ans = 0.8660) 2. tan(45*pi/180 ) (ans = 1.0000) 3. Sin(pi)+cos(45*pi/180 ) (ans = 0.7071)

The format

Function

The format function is used to control how the numeric values are displayed in the Command Window. The short format is set by default

and the numerical results are displayed with 4 digits after the decimal point (see the examples above). The Long format produces 15 digits after the decimal point.

Example: Calculate 0 = tan(4) and display results in short and Long formats. The short format is set by default:

>> theta=tan(pi/3) theta = 732i >> And the Long format is tumed on by typing Format long: >> theta=tan(pi/3) theta = W. 732i

>> format long >> theta

theta =

1.732050807568877

Variables

In MATLAB, a named value is called a variable. MATLAB comes with several predefined variables. For example, the name pi refers to the mathematical quantity m, which is approximately pl ans = 3.1416

Note:MATLAB is case-sensitive, which means it distinguishes between upper- and lowercase letters (e.g. data, DATA and DaTa are three different variables). Command and function names are also case-sensitive. Please note that when you use the command-line help, function names are given in upper-case letters (e.g., CLEAR) only to emphasize them. Do not use upper-case letters when running functions and commands.

Declaring Variables

Variables in MATLAB are generally represented as matrix quantities. Scalars and vectors are special cases of matrices having size 1x1 (scalar), 1xn (row vector) or nx1 (column vector).

Declaration of a Scalar

The term scalar as used in linear algebra refers to a real number. Assignment of scalars in MATLAB is easy, type in the variable name followed by = symbol and a number:

Example: a=1

Comma indo =

Assignment of a scalar quantity.

Declaration of a Row Vector

Elements of a row vector are separated with blanks or commas.

>> b=(1 2 3 4 5]

Assignment of a row vector quantity.

We can also use the New Variable button to assign a row vector. In the tool strip, select Home > New Variable. This action will create a variable called unnamed which is displayed in the workspace. By clicking on the title unnamed, we can rename it to something more descriptive. By double-

clicking on the variable, we can open the Variable Editor and type in the values into spreadsheet looking table.

L Temporaryltems » 2008 » builds } Custom Office Templates

-OmMMandG MIstory %-- 03/06/2015 09:...

Select a file to view details

Using the New Variable button in the tool strip.

@ \) $RECYCLE.BIN ) Temporaryltems

woont DH wn

%-- 03/06/2015 09:...

=y So

clc

pe —— = 7 | b me Ol nd Windo\

Select a file to view details

Assignment of a row vector by using the Variable Editor.

Declaration of a Column Vector

Elements of a column vector is ended by a semicolon:

Example: cf) 27374,5,1

Assignment of a column vector quantity.

>> o=[1 2 34 5]*

c=

Ob © he be

Assignment of a column vector quantity by transposing a row vector with the ' operator.

Or by using the Variable Editor:

@ J) $RECYCLE.BIN L Temporaryltems = [1,2,3,4,5] ® )) 2008 : SE 11;23;4:51 » builds -

} Custom Office Templates

OMMANG MIStory %-- 03/06/2015 09:... clc

Details

Select a file to view details

Assignment of a column vector quantity by using the Variable Editor.

Declaration of a Matrix

Matrices are typed in rows first and separated by semicolons to create columns. Consider the examples below:

Example: Let us type in a 2x5 matrix: dis [27 46-8 1043757, 9]

>> d=[2 46610; 135 7 9]

Assignment of a 2x5 matrix.

a | ei a

© ) $RECYCLE.BIN ;

) Temporaryltems : ' [1,2,3,4,5]

& § 2008 (1;2;3;4;5]

@ |) builds § ze [2,4,6,8,10;13,5,7... } Custom Office Templates

Desktop

& |) Documents

Assignment of a matrix by using the Variable Editor.

Example:

This example is a 5x2 matrix:

Command Window oo oe >> e = [2 43 6 B83 10 123 14 167 18 20]

2 4 6 8 10 12 14 16 18 20

Assignment of a 5x2 matrix.

Linear Equations

Systems of linear equations are very important in engineering studies. In the course of solving a problem, we often reduce the problem to simultaneous equations from which the results are obtained. As you learned earlier, MATLAB stands for Matrix Laboratory and has features to handle matrices. Using the coefficients of simultaneous linear equations, a matrix can be formed to solve a set of simultaneous equations.

Example: Let's solve the following simultaneous equations: Equation:

oy — 1 Equation:

22 — oy = 9

First, we will create a matrix for the left-hand side of the equation using the coefficients, namely 1 and 1 for the first and 2 and -5 for the second. The matrix looks like this:

it

lhe =)

Equation: The above matrix can be entered in the command window by typing A=[ 1 el |. Second, we create a column vector to represent the right-hand side of the equation as follows:

1

9

Equation:

The above column vector can be entered in the command window by typing B= [1;9].

To solve the simultaneous equation, we will use the left division operator and issue the following command: C=A\B. These three steps are illustrated below:

>> A=[1 1; 2 -5]

——

il 1

2 -5 >> B= [1;9] B=

1

>>

The result C indicating 2 and 1 are the values for x and y, respectively.

Polynomials

In the preceding section, we briefly learned about how to use MATLAB to solve linear equations. Equally important in engineering problem solving is the application of polynomials. Polynomials are functions that are built by simply adding together (or subtracting) some power functions. (see Wikipedia).

Equation:

az’ + br +c=0 Equation: f(x) = az? + br +c

The coeffcients of a polynominal are entered as a row vector beginning with the highest power and including the ones that are equal to 0.

Example: Create a row vector for the following function: y = 224+ 32° 4+ 5a? +2410

Notice that in this example we have 5 terms in the function and therefore the row vector will contain 5 elements. p=[2 3 5 1 10]

Example:

Create a row vector for the following function: y = 3a* + 4x? — 5

In this example, coefficients for the terms involving power of 3 and 1 are 0. The row vector still contains 5 elements as in the previous example but this time we will enter two zeros for the coefficients with power of 3 and 1: p=[3 0 4 0 -5].

The polyval Function

We can evaluate a polynomial p for a given value of X using the syntax polyval(p, x) where p contains the coefficients of polynomial and x is the given number.

Example: Evaluate f(x) at 5. Equation:

f(x) = a+ 2x4 1

The row vector representing f(x) above is p=[3 2 1]. To evaluate f(x) at 5, we type in: polyval(p, 5). The following shows the Command Window output:

>> p=[3 2 1]

>> polyval(p,5) ans = 86

>>

The roots Function

Consider the following equation: Equation:

ax? + br +c=0

Probably you have solved this type of equations numerous times. In MATLAB, we can use the roots function to find the roots very easily.

Example: Find the roots for the following: Equation:

0.627 + 0.32 — 0.9 =0

To find the roots, first we enter the coefficients of polynomial in to a row vector p with p=[0.6 ©.3 -0©.9] and issue the r=roots(p) command. The following shows the command window output:

>> p=[0.6 0.3 -0.9] p = 0.6000 0.3000 -0.9000

>> r=roots(p)

>>

Splitting a Statement

You will soon find out that typing long statements in the Command Window or in the the Text Editor makes it very hard to read and maintain your code. To split a long statement over multiple lines simply enter three periods "..." at the end of the line and carry on with your statement on the next line.

Example: The following command window output illustrates the use of three periods:

>> Sin(pi)+cos(45*pi/180) - Sin(pi/2)+cos(45*pi/180)+tan(pi/3)

ans = 2.1463

>> Sin(pi)t+cos(45*pi/180)-sin(pi/2)... +cos(45*pi/180)+tan(pi/3)

ans = 2.1463

>>

Comments

Comments are used to make scripts more "readable". The percent symbol % separates the comments from the code. Examine the following examples:

Example:

The long statements are split to make it easier to read. However, despite the use of descriptive variable names, it is hard to understand what this script does, see the following Command Window output:

t_water=80; t_outside=15; inner_dia=0.05; thickness=0.006; Lambda_steel=48;

AlfaInside=2800; AlfaOutside=17; thickness_insulation=0.012; Lambda_insulation=0.03;

r_i=inner_dia/2 r_o=r_it+thickness r_i_insulation=r_o r_o_insulation=r_i_insulation+thickness_insulation AreaInside=2*pi*r_i AreaOutside=2*pi*r_o AreaOutside_insulated=2*pi*r_o_insulation AreaM_pipe=(2*pi*(r_o-r_1))/log(r_o/r_i) AreaM_insulation=(2*pi*(r_o_insulation- r_i_ insulation) ) /log(r_o_insulation/r_i_ insulation) TotalResistance=(1/(AlfaInside*AreaInside) )+ (thickness/(Lambda_steel*AreaM_pipe) )+ (1/7(ALfaOutside*AreaOutside) ) TotalResistance_insulated= (1/7(AlfaInside*AreaInside) )+ ... (thickness/(Lambda_steel*AreaM_pipe) )+ (thickness_insulation /(Lambda_insulation*AreaM_insulation) )+ (1/(AlLfaOutside*AreaOutside_insulated) ) Q dot=(t_water-t_outside)/(TotalResistance*1000) Q dot_insulated=(t_water - t_outside)/(TotalResistance_insulated*1000 ) PercentageReducttion=((Q_dot- Q dot_insulated)/Q_dot)*100

Example: The following is an edited version of the above including numerous comments:

% Problem 16.06

% Problem Statement

% Calculate the percentage reduction in heat loss when a layer of hair felt

% 1S wrapped around the outside surface (see problem 16.05)

Format short

% Input Values

t_water=80; % Water temperature [C] t_outside=15; % Atmospheric temperature [C] inner_dia=0.05; % Inner diameter [m] thickness=0.006; % [m]

Lambda_steel=48; % Thermal conductivity of steel [W/mK]

AlfaInside=2800; % Heat transfer coefficient of inside [W/m2K]

AlfaOutside=17; % Heat transfer coefficient of

outside