Thursday, June 7, 2012

MATLAB Essentials

MATLAB Essentials

Summary: Essential skills to use MATLAB effectively.
MATLAB Essentials
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:
TABLE 1: Operators
/Forward SlashDivision
\Back SlashLeft Matrix Division
.*Dot AsteriskArray multiplication (element-wise)
./Dot SlashRight array divide (element-wise)
.\Dot Back SlashLeft array divide (element-wise)
.^Dot CaretArray power (element-wise)


The backslash operator is used to solve linear systems of equations, see Section 12.


Matrix is a rectangular array of numbers and formed by rows and columns. For example A=( 1234 5678 9101112 13141516 ) . In this example A consists of 4 rows and 4 columns and therefore is a 4x4 matrix. (see Wikipedia).


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=( 12345 )


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 number of elements in the column vector. C=( 1 2 3 4 5 )


Array operations refer to element-wise calculations on the arrays, for example if x is an a by b matrix and y is a c 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 rows and 3 columns and an array operation is possible. x=( 123 456 ) and y=( 102030 405060 ) then x.*y=( 104090 160250360 )


The following figure illustrates a typical calculation in the Command Window.
Figure 1: Basic arithmetic in the command window.

Operator Precedence

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.


Typing pi returns the number 3.1416. To find the sine of pi, type in sin(pi) and press enter.


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


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


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 help and doc pages for functions that are not self explanatory.


Calculate the following quantities:
  1. 23321 ,
  2. 50.51
  3. π4d2 for d=2
MATLAB inputs and outputs are as follows:
  1. 23321 is entered by typing 2^3/(3^2-1) (ans = 1)
  2. 50.51 is entered by typing sqrt(5)-1 (ans = 1.2361)
  3. π4d2 for d=2 is entered by typing pi/4*2^2 (ans = 3.1416)


Calculate the following exponential and logarithmic quantities:
  1. e2
  2. ln510
  3. log105
MATLAB inputs and outputs are as follows:
  1. exp(2) (ans = 7.3891)
  2. log((5^10)) (ans = 16.0944)
  3. log10(10^5) (ans = 5)


Calculate the following trigonometric quantities:
  1. cosπ6
  2. tan45
  3. sinπ+cos45
MATLAB inputs and outputs are as follows:
  1. cos(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.


Calculate θ=tanπ3 and display results in short and long formats.
The short format is set by default:
>> theta=(pi/3)

theta =


And the long format is turned on by typing format long:
>> theta=(pi/3)

theta =


>> format long
>> theta

theta =




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 π, which is approximately pi ans = 3.1416


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:
a = 1
Figure 2: Assignment of a scalar quantity.

Declaration of a Row Vector

Elements of a row vector are separated with blanks or commas.
Let's type the following at the command prompt:
b = [1 2 3 4 5]
Figure 3: Assignment of a row vector quantity.

We can also use the Variable Editor to assign a row vector. In the menu bar, select File > 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.
Figure 4: 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:
c = [1;2;3;4;5;]
Figure 5: Assignment of a column vector quantity.

Or by transposing a row vector with the ' operator:
c = [1 2 3 4 5]'
Figure 6: Assignment of a column vector quantity by transposing a row vector with the ' operator.

Or by using the Variable Editor:
Figure 7: 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:
Let us type in a 2x5 matrix:
d = [2 4 6 8 10; 1 3 5 7 9]
Figure 8: Assignment of a 2x5 matrix.

Figure 9: Assignment of a matrix by using the Variable Editor.
This example is a 5x2 matrix:
Figure 10: 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.


Let's solve the following simultaneous equations:
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:
( 11 25 )
The above matrix can be entered in the command window by typing A=[1 1; 2 -5].
Second, we create a column vector to represent the right-hand side of the equation as follows:
( 1 9 )
The above column vector can be entered in the command window by typing B= [1;9].
To solve the simultaneous equation, we will use left division operator and issue the following command: C=A\B. These three steps are illustrated below:
>> A=[1 1; 2 -5]

A =

     1     1
     2    -5

>> B= [1;9]

B =


>> C=A\B

C =


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


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


Create a row vector for the following function: y=2x4+3x3+5x2+x+10
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]


Create a row vector for the following function: y=3x4+4x25
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.


Evaluate f(x) at 5.
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]

p =

     3     2     1

>> polyval(p,5)

ans =



The roots Function

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


Find the roots for the following:
To find the roots, first we enter the coefficients of polynomial in to a row vector p with p=[0.6 0.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)

r =



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.


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 =


>> sin(pi)+cos(45*pi/180)-sin(pi/2)...

ans =




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


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:

AreaM_insulation=(2*pi*(r_o_insulation-r_i_insulation)) ...
TotalResistance=(1/(AlfaInside*AreaInside))+ ...
TotalResistance_insulated=(1/(AlfaInside*AreaInside))+ ...
    (thickness/(Lambda_steel*AreaM_pipe))+(thickness_insulation ...


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
% is 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 [W/m2K]
% Neglect radiation
% Additional layer
thickness_insulation=0.012;     % [m]
Lambda_insulation=0.03;         % Thermal conductivity of insulation [W/mK]

% Output Values
% Q_dot=(t_water-t_outside)/TotalResistance
% TotalResistance=(1/(AlfaInside*AreaInside))+(thickness/(Lambda_steel*AreaM))+ ...
% Calculating the unknown terms
r_i=inner_dia/2                                         % Inner radius of pipe [m]
r_o=r_i+thickness                                       % Outer radius of pipe [m]
r_i_insulation=r_o                                      % Inner radius of insulation [m]
r_o_insulation=r_i_insulation+thickness_insulation      % Outer radius of pipe [m]
AreaM_pipe=(2*pi*(r_o-r_i))/log(r_o/r_i)                % Logarithmic mean area for pipe
AreaM_insulation=(2*pi*(r_o_insulation-r_i_insulation)) ...
    /log(r_o_insulation/r_i_insulation)    % Logarithmic mean area for insulation
TotalResistance=(1/(AlfaInside*AreaInside))+(thickness/ ...
TotalResistance_insulated=(1/(AlfaInside*AreaInside))+(thickness/ ...
    (Lambda_steel*AreaM_pipe))+(thickness_insulation/(Lambda_insulation*AreaM_insulation)) ...
Q_dot=(t_water-t_outside)/(TotalResistance*1000) % converting into kW
Q_dot_insulated=(t_water-t_outside)/(TotalResistance_insulated*1000) % converting into kW

Basic Operations

TABLE 2: Basic operations.
sumSum of array elements
prodProduct of array elements
sqrtSquare root
log10Common logarithm (base 10)
logNatural logarithm
maxMaximum elements of array
minMinimum elements of array
meanAverage or mean value of arrays
stdStandard deviation

Special Characters

TABLE 3: Special Characters
( )Prioritize operations
[ ]Construct array
:Specify range of array elements
,Row element separator in an array
;Column element separator in an array
...Continue statement to next line
.Decimal point, or structure field separator
%Insert comment line into code

Summary of Key Points

  1. MATLAB has the common functions found on a scientific calculator and can be operated in a similar way,
  2. MATLAB can store values in variables. Variables are case sensitive and some variables are reserved by MATLAB (e.g. pi stores 3.1416),
  3. Variable Editor can be used to enter or manipulate matrices,
  4. The coefficients of simultaneous linear equations and polynomials are used to form a row vector. MATLAB then can be used to solve the equations,
  5. The format function is used to control the number of digits displayed,
  6. Three periods "..." at the end of the line is used to split a long statement over multiple lines,
  7. The percent symbol % separates the comments from the code, anything following % symbol is ignored by MATLAB.

No comments:

Post a Comment