Sie sind auf Seite 1von 39

MATLAB

ECP 281: ENGINEERING COMPUTER


PROGRAMMING – PART 1
Introduction
• MATLAB is an incredibly powerful tool,
but in order to use it safely you need to
be able to understand how it works and
to be very precise when you enter
commands.
• Changing the way you enter a command,
even subtly can completely change its
meaning.
• MATLAB uses an interpreter to try to understand
what you type and this can come back with
suggestions as to where you might have gone
wrong: sometimes what you have written makes
sense to MATLAB but does not mean what you
expect!
• So you need to be careful.
• It is crucial that you formulate ideas clearly in
your head (or on paper) before trying to translate
them into MATLAB (or any other language).
BASIC CONCEPTS
1. Display Windows
MATLAB has three display windows. They are
1. A Command Window which is used to enter commands and data to display plots and
graphs.
2. A Graphics Window which is used to display plots and graphs.
3. An Edit Window which is used to create and modify M-files. M-files are files that contain
a
program or script of MATLAB commands.
2. Entering Commands
Every command has to be followed by a carriage return <cr> (enter key) in order that the
command can be
executed. MATLAB commands are case sensitive and lower case letters are used
throughout.
3. MATLAB Expo
In order to see some of the MATLAB capabilities, enter the demo command. This will
initiate the MATLAB
EXPO. MATLAB EXPO is a graphical demonstration environment that shows some of the
different types of
operations which can be conducted with MATLAB.
4. Abort
In order to abort a command in MATLAB, hold down the control key and press c to
generate a local abort with
MATLAB.
5. Statements and Variables
Statements have the form
>> variable = expression
The equals (“=”) sign implies the assignment of the expression to the variable.
6. The Semicolon (;)
If a semicolon (;) is typed at the end of a command, the output of the command is
not displayed.
7. Typing %
When per cent symbol (%) is typed in the beginning of a line, the line is designated
as a comment. When the enter key is pressed, the line is not executed.
8. The clc Command
Typing clc command and pressing enter cleans the command window. Once the clc
command is executed, a clear window is displayed.
9. Help
MATLAB has a host of built-in functions. For a complete list, refer to MATLAB user’s
guide or refer to the on-line Help. To obtain help on a particular topic in the list,
e.g., inverse, type help inv.
Table 1: Display formats
Table 2: Common math functions
Table 3: Round off functions
Table 4: Workspace Information
Rules For Naming Variables In
Matlab
1. Variable names in MATLAB must start with a letter and
can be up to 31 characters long. The trailing characters
can be numbers, letters or underscores (some other
characters are also available but in this text we shall
stick to these). There are many choices which are
forbidden as variable names, some for very obvious
reasons (such as a*b which signifies a multiplication of
the variables a and b) and others for more subtle
reasons.
2. Variable names in MATLAB are case
sensitive, so that a and A are two
different objects.
3. It is good programming practice to
employ meaningful variable names.
4. Variables names should not coincide with
a predefined MATLAB command or with
any user-defined subroutines.
Order Of Calculations Performed

•• This represents one of the most common sources of


errors and it is often the most difficult to detect.
• For example the commands (3+4/5) and (3+4)/5
are obviously different, the former being 3 4/5 and
the latter being .
• We should note that in the syntax of MATLAB a/b*c
is not equal to but .
• In order to ensure that the denominator of the
fraction is calculated first we would need to use a/
(b*c), which is equal to a/bc . Similarly for examples
like a/b+c versus a/(b+c).
• Understand these:

• 1+2/3*4-5
• 1/2/3/4
• 1/2+3/4*5
• 5-2*3*(2+7)
• (1+3)*(2-3)/3*4
• (2-3*(4-3))*4/5
Do these:

•, where a=1, b=2, c=3.


Do these:
• Using x values ranging from 0 to 2rads in steps of 0.01rad; plot the
following expressions on the same figure.

• y2 = 1/x + x^3/(x^4 + 5x sin x)

• y4 = sin2xcosx + x sin3xcos 4x
Arrays
An array is a list of numbers arranged in rows and/or columns. A one-
dimensional array is a row or a column of numbers and a two-dimensional
array has a set of numbers arranged in rows and columns. An array
operation is performed element-by-element.
1. Row Vector
A vector is a row or column of elements. In a row vector, the elements are
entered with a space or a comma between the elements inside the square
brackets. For example, x = [7 –1 2 –5 8].
2. Column Vector
In a column vector, the elements are entered with a semicolon between
the elements inside the square brackets. For example, x = [7; –1; 2; –5; 8].
Matrix
A matrix is a two-dimensional array which has numbers in rows and
columns. A matrix is entered row-wise with consecutive elements of a
row separated by a space or a comma, and the rows separated by
semicolons or carriage returns. The entire matrix is enclosed within
square brackets. The elements of the matrix may be real numbers or
complex numbers.
Colon for a vector
Va(:) – refers to all the elements of the vector Va (either a row or a column vector).
Va(m:n) – refers to elements m through n of the vector Va.
For instance,
>> V = [2 5 –1 11 8 4 7 –3 11]
>> u = V (2 :8)
u = 5 –1 11 8 4 7 –3 11
Colon for a matrix
Table 5 gives the use of a colon in addressing arrays in a matrix.
Vectors in Matlab
• R=1:5 This sets the variable R to be equal to the vector [1 2
3 4 5]
• We can change the step by using the slightly more involved
syntax r = a:h:b, which creates the vector r running from a
to b in steps of h.
• We can also initiate vectors by typing the individual entries;
this is especially useful if the data is irregular, for instance t
= [14 20 27 10];
• We can use the linspace command also e.g t =
linspace(0,1,10);
Arithmetic manipulations between
vectors
• s = 1:10;
• t = -1:-2:-19;
• s+t
• s-t
• s.*t
• s./t
• s.ˆ2
• 1./s
• s/2
• s+1
Some matlab specific commands
• The polyval (y = polyval(c,x)): This command takes two inputs,
namely the coefficients of a polynomial and the values at which
you want to evaluate it.
• Evaluate the cubic y = x^3 + 3x^2 − x − 1 at the points x =(1, 2,
3, 4, 5, 6).
• The roots (y=roots(c)); Find the roots of the polynomial y =
x^3 − 3x^2 + 2x
• Accessing elements in an array: Let us start by considering a
simple array x = 0:0.1:1.;. The elements of this array can be
recalled by using the format x(1) through to x(11).
Example: Write a code to determine the currency which
has shown the smallest proportional change in the value
in relation to sterling between year 1 and year 2
Table 6: Value of £1 Sterling (GBP)
Currency Year 1 Year 2
Euro (EUR) 1.52 1.64
US Dollar (USD) 1.60 1.45
Japanese yen (JPY) 158 190
Australian dollar (AUD) 2.55 2.71
Swiss Franc (CHF) 2.60 2.40
Hong Kong dollar 12.3 11.2
(HKD)
Malaysian Ringgit 7.6 5.45
(MYR)
Operations of Matrices
1. Addition and Subtraction: The addition (the sum) or the subtraction (the
difference) of the two arrays is obtained by adding or subtracting their
corresponding elements. These operations are performed with arrays of
identical size (same number of rows and columns).
2. Dot Product: dot(A, B): Computes the dot product of A and B. If A and B are
matrices, t0he dot product is a row vector containing the dot products for the
corresponding columns of A and B.
3. Identity matrix: An identity matrix is a square matrix in which all the
diagonal elements are 1’s, and the remaining elements are 0’s. If a matrix A is
square, then it can be multiplied by the identity matrix, I, from the left or from
the right: AI = IA = A
4. Inverse of a matrix: The matrix B is the inverse of the matrix A when the
two matrices are multiplied and the product is an identity matrix. Both
matrices A and B must be square and the order of multiplication can be AB or
BA. AB = BA = I
6. Transpose of a matrix: The transpose of a matrix is a new matrix in which the
rows of the original matrix are the columns of the newmatrix. The transpose of
a given matrix A is denoted by AT. In MATLAB, the transpose of the matrix A is
denoted by A′.
7. Determinant: A determinant is a scalar computed from the entries in a
square matrix. For a 2 × 2 matrix A, the determinant is |A| = a11 a22 – a21 a12.
MATLAB will compute the determinant of a matrix using the det function:
det(A): Computes the determinant of a square matrix A.
8. Array Division: MATLAB has two types of array division, namely: the right
array division (B/A) and the left array division (A\B).
9. Eigenvalues and Eigenvectors: Consider the following equation:
AX = λX
where A is an n × n square matrix, X is a column vector with n rows and λ is a
scalar. The values of λ for which X are non-zero are called the eigenvalues of the
matrix A, and the corresponding values of X are called the eigenvectors of the
matrix A.
System of Linear Equations
• A system of equations is non-singular if the matrix A containing the coefficients of
the equations is nonsingular. A system of non-singular simultaneous linear equations
(AX = B) can be solved using two methods:
(a) Matrix Division Method.
(b) Matrix Inversion Method.
• Matrix Division
The solution to the matrix equation AX = B is obtained using matrix division, or X =
A/B. The vector X then contains the values of x.
• Matrix Inverse
For the solution of the matrix equation AX = B, we pre-multiply both sides of the
equation by A-1.
A-1AX = A-1B or IX = A-1B, where I is the identity matrix.
Hence X = A-1B
In MATLAB, we use the command x = inv (A)*B. Similarly, for XA = B, we use the
command x = B * inv (A).
Matrix Operations
•and
Using MATLAB, determine the following:
(a) A + B
(b) AB
(c) A2
(d) AT
(e) B-1
(f ) BTAT
(g) (A2)T + (BT)2 – AB
(h) determinant of A, determinant of B and determinant of AB.
(i) Determine the eigenvectors and eigenvalues of A and B
System of Equations
Determine the values of x1, x2, x3 and x4 for the following set of linear algebraic equations:
1. x2 – 3x3 = –5
2x1 + 3x2 – x3 = 7
4x1 + 5x2 – 2x3 = 10

2. x1 + 2x2 + 3x3 + 5x4 = 21


–2x1 + 5x2 + 7x3 – 9x4 = 18
5x1 + 7x2 + 2x3 – 5x4 = 25
–x1 + 3x2 – 7x3 + 7x4 = 30
Graphics
• MATLAB has many commands that can be used to create basic 2-D plots,
overlay plots, specialized 2-D plots, 3-D plots, mesh and surface plots.

Basic 2-D Plots


• The basic command for producing a simple 2-D plot is
plot(x values, y values, ‘style option’)
where
• x values and y values are vectors containing the x- and y-coordinates of
points on the graph.
• Style option is an optional argument that specifies the color, line-style
and the point-marker style.
Graphics Continuation
• The style option in the plot command is a character string that
consists of 1, 2 or 3 characters that specify the color and/or the line
style.
• The different color, line-style and marker-style options are
summarized in Table 7.
Specialized 2-D Plots

• There are several specialized graphics functions available in MATLAB


for 2-D plots. The list of functions commonly used in MATLAB for
plotting x-y data are given in Table 8.
Example: Generate an overlay plot
for plotting three lines

• + 0 ≤ t ≤ 2π
Do these
1. Use the functions for plotting x-y data for plotting the following
function:
f (t) = tcost; 0 ≤ t ≤ 10π
Plot the following functions on the same plot for 0 ≤ x ≤ 2π using the
plot function:
(a) Sin2(x)
(b) Cos2(x)
(c) cos(x)
Creating Script and Functions
• A script is simply a file containing the sequence of MATLAB commands
which we wish to execute to solve the task at hand; in other words a
script is a computer program written in the language of MATLAB.
• To invoke the MATLAB editor we type edit at the prompt. This editor
has the advantage of understanding MATLAB syntax and producing
automatic formatting (for instance indenting pieces of code as
necessary).
• It is also useful for colour coding the MATLAB commands and
variables.
• Both of these attributes are extremely useful when it comes to
debugging code.
Setting up your editor
• Clc
• Clear all
• Input command: input(str)
• Display command: disp(str)
Functions
• These codes take inputs and return outputs.
function [output] = xsq(input)
output = input.ˆ2;
• The first line of xsq.m tells us this is a function called xsq which takes an
input called input and returns a value called output.
• The input is contained in round brackets, whereas the output is
contained within square brackets.
• It is crucial for good practice that the name of the function xsq
corresponds to the name of the file xsq.m (without the .m extension).
• The second line of this function actually performs the calculation, in
this case squaring the value of the input, and storing this result in the
variable output.
Do these (NB: 1 mile = 1760 yards; 1 yard = 36 inches; 1 inch =
2.54 cm; 1 m = 100cm)
• (a) Construct a code which converts a speed in miles
per hour to kilometres per hour.

• (b) Write a code which converts metres per second to


miles per hour and use it to determine how fast a
sprinter who runs the 100 metres in 10 seconds is
travelling in miles per hour (on average).

• (c) Rewrite your code from part (a) so that it is now a


function that takes a single input, the speed in miles
per hour, and returns a single output, the speed in
kilometres per hour.
Assignment 1
•1. With user-input prompt, write a code to solve quadratic
equations using the almighty formula.
2. The functions f(x) and g(x) are defined by f(x) = and g(x) = tan
x. Write MATLAB codes to calculate these functions and plot
them on the interval (−π/2, π/2). Also plot the functions
f(g(x)) and g(f(x)) on this interval.
3. Write a code which enables a user to input the coefficients of a
quadratic function q(x) = ax2 + bx + c and plot the function
q(x) for x = sin(y) where y ∈ [0, π].
•4. The deflection y of a beam at distance x from one end is given by

• where a = , E being the Young’s modulus of the beam, and I is the


moment of inertia of a cross-section of the beam. The beam is 10 m
long, the tension is 1000 N, the load 100 N/m, and EI is 104 Nm2.
• Write a script to compute and plot a graph of the deflection y
against x (MATLAB has a cosh function). To make the graph look
realistic you will have to override MATLAB’s automatic axis
scaling with the statement axis([xmin xmax ymin ymax]) after the
plot statement, where xmin etc. have appropriate values. Take x =
101 values from 0 to 3m.

Das könnte Ihnen auch gefallen