Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
38 views

Chapter 1 - Basic Programming, Matrices and Arrays, Functions, Plotting, 2D, 3D

The document describes a scientific computing course covering basic programming in MATLAB including the MATLAB environment, functions, arrays, graphics, and mathematical modeling. It provides the course outline, textbooks, and modes of assessment.

Uploaded by

teddy jeremy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views

Chapter 1 - Basic Programming, Matrices and Arrays, Functions, Plotting, 2D, 3D

The document describes a scientific computing course covering basic programming in MATLAB including the MATLAB environment, functions, arrays, graphics, and mathematical modeling. It provides the course outline, textbooks, and modes of assessment.

Uploaded by

teddy jeremy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 73

BCSC 2207 SCIENTIFIC COMPUTING

CUK

Anthony Mile (PhD)


Contact: 0715594957
mileanthony@yahoo.com
• An interdisciplinary field
• SC requires knowledge of the
subject of the underlying
problem to be solved, a
mathematical modeling
capability with a sound idea of
various numerical analysis
techniques, and finally its
efficient and high-performance
implementation using
computing techniques.

• In comp. science, SC can be considered a numerical simulation of a


mathematical model
Course Outline
• Basic programming: Introduction to the MATLAB environment and the
MATLAB help system, data types and scalar variables, arithmetic and
mathematical functions, input and output, selection and iteration
statements.
• Functions: user defined functions, function files, passing information to
and from functions, function design and program decomposition,
recursion.
• Arrays: vectors, arrays and matrices, array addressing, vector, matrix
and element-by-element operations.
• Graphics: 2-D and 3-D plotting. Mathematical modelling: dynamical
systems, linear systems, numerical differentiation and integration.
• Spreadsheets: Spreadsheets as a tool for Scientific Computing:
calculation, using in-built functions, plotting and fitting, modelling and
optimisation using the Goal-Seek and Solver tools, data analysis.
Course Textbooks
• Bertil Gustafsson, Fundamentals of Scientific Computing, Springer Science & Business
Media, 2011, ISBN 9783642194955.
• Michael T. Heath, Scientific Computing: An Introductory Survey. McGraw-Hill, 1997, ISBN
9780070276840
• Hemant Kumar Mehta, Mastering Python Scientific Computing, Packt Publishing Ltd,
2015, ISBN 9781783288830

Reference Text Books


• Dianne P. O'Leary, (2009). Scientific Computing with Case Studies. SIAM ISBN
9780898716665
• Bertil Gustafsson,(2011). Fundamentals of Scientific Computing, Springer Science.
Business Media,ISBN 9783642194955
• William H. Press, Saul A. Teukolsky, William T. Vetterling, Brian P. Flannery (1996).
Numerical Recipes in C: The Art of Scientific Computing, Cambridge University Press,
ISBN 9780521576086
Modes of study

• Lectures, Lab sessions, group based presentations/learning

• Assessment:
o Lab Assignment/Exercises/Takeaway– 30%
o End Semester Exam – 70%
Basic Programming

in MATLAB
Introd. to MATLAB Environment

• MATLAB is a program for doing numerical computation.


• Was originally designed for solving linear algebra type
problems using matrices. It’s name is derived from MATrix
LABoratory.
• Its both a computer programming language, and a
software environment for using that language effectively.
• Its well adapted to numerical experiments
• Matlab program and script files (m-files) always have
filenames ending with ".m“
• The programming language is exceptionally
straightforward since almost every data object is
assumed to be an array.
Many uses of Matlab

• Math and computation


• Algorithm development
• Modeling, simulation, and prototyping
• Data analysis, exploration, and visualization
• Scientific and engineering graphics

It has powerful graphical capabilities that provide for 2D


and 3D graphics and even animation.
Why Use Matlab

• Advantages:
– Handles vector and matrices very nice
– Quick plotting and analysis
– EXTENSIVE documentation (type “help”)
– Lots of nice functions: FFT, fuzzy logic, neural nets,
numerical integration, OpenGL
• Drawbacks:
– Slow compared to C or Java
MATLAB is not:
❑ not a computer algebra system
❑ not a strong general purpose programming language
• limited support for other data structures
• few software-engineering features;
typical MATLAB programs are only a few lines long
• not well-suited for teaching OOP
• limited GUI features
❑ not a high-performance language (but fast matrix operators)
❑ not freely available (but local campus license)
Introd. to MATLAB Environment

• Graphical output (figure) is available to supplement


numerical results.
• Online help - Typing help on the matlab prompt (a
double arrow)
• MATLAB has since been expanded and now has built-in
functions for solving problems requiring data analysis,
signal processing, optimization, and several other types
of scientific computations. It also contains functions for
2-D and 3-D graphics and animation.
MATLAB

• The MATLAB environment is command oriented somewhat


like UNIX. A prompt appears on the screen and a MATLAB
statement can be entered. When the <ENTER> key is
pressed, the statement is executed, and another prompt
appears.
• If a statement is terminated with a semicolon ( ; ), no
results will be displayed. Otherwise results will appear
before the next prompt.
MATLAB Dev’pmt Environ. & Basic Math Functions
Run the Matlab
MATLAB Dev’pmt Environ.
Documentation/Help System

• Full documentation built in: start matlab then type


o doc – to browse built-in hypertext manual
o doc command – to jump to a specific manual page (e.g.
plot)
o help command – to show plain-text summary of a
command
• Read first: doc → MATLAB → Getting Started
• Tutorial videos:
https://uk.mathworks.com/videos/
• Documentation also available online (HTML and PDF):
o https://uk.mathworks.com/help/matlab/
o https://uk.mathworks.com/help/ – toolboxes

Locally installed MATLAB may be behind the latest release


MATLAB Variable Names

• MATLAB variable names must begin with a letter,


which may be followed by any combination of letters,
digits, and underscores. MATLAB distinguishes
between uppercase and lowercase characters, so A
and a are not the same variable(case sensitive).
• When naming a variable, make sure you are not using
a name that is already used as a function name, begin
with character .
MATLAB Special Variables

ans Default variable name for results/most recent answer


(variable). If you do not assign an output variable to an
expression, MATLAB automatically stores the result in ans.
beep Beep sound
pi Value of  (3.1415926535897..)
eps Smallest incremental number
inf Infinity. Calculations like n/0, where n is any nonzero real
value, result in inf.
NaN Not a number e.g. Expressions like 0/0 and inf/inf
i and j i = j = square root of -1
Realmin Minimum real number that can be used. Approx 2 *10^(-308)
Realmax Maximum real number that can be used.Approx 1.8*10^(308
e Eulers constant
MATLAB Math Operators

• Arithmetic
– numeric computations, e.g., 2^10
• Relational
– quantitative comparison of operands
– e.g., a < b
• Logical
– AND, OR, NOT
return Boolean variable, 1 (TRUE) or 0 (FALSE)
Arithmetic Operators
MATLAB Relational Operators

• MATLAB supports six relational operators.

Less Than <


Less Than or Equal <=
Greater Than >
Greater Than or Equal >=
Equal To ==
Not Equal To ~=
Examples
MATLAB Logical Operators

• MATLAB supports three logical operators.

not ~ % highest precedence


and & % equal precedence with or
or | % equal precedence with and
MATLAB Logical Functions
xor (exclusive or) Ex: xor (a, b)
Where a and b are logical expressions. The xor
operator evaluates to true if and only if one
expression is true and the other is false. True is
returned as 1, false as 0.
any (x) returns 1 if any element of x is nonzero
all (x) returns 1 if all elements of x are nonzero
isnan (x) returns 1 at each NaN in x
isinf (x) returns 1 at each infinity in x
finite (x) returns 1 at each finite value in x
Logical Operators
Examples
Example (Arithmetic Operator)
To get started, type one of these commands: helpwin,
helpdesk, or demo

» a=5;
» b=a/2

b=

2.5000

»
Other MATLAB symbols

>> prompt
... continue statement on next line
, separate statements and data
% start comment which ends at end of line
; (1) suppress output
(2) used as a row separator in a matrix
: specify range
MATLAB Matrices

• MATLAB treats all variables as matrices. For our purposes a


matrix can be thought of as an array, in fact, that is how it is
stored.
• Vectors are special forms of matrices and contain only one
row OR one column. A vector is a quantity that is
defined by multiple scalars. In addition to magnitude,
a vector also has a direction.
• Scalars are matrices with only one row AND one column.
A scalar is a quantity expressed by a single real number e.g.
Length
MATLAB Matrices

• A scalar can be created in MATLAB as follows:


» a_value=23
a_value =
23
• A row vector can be created in MATLAB as follows (note
the commas):
» rowvec = [12 , 14 , 63]
rowvec =
12 14 63
MATLAB Matrices
• A matrix with only one column is called a column vector. A
column vector can be created in MATLAB as follows (note the
semicolons):

» colvec = [13 ; 45 ; -2]

colvec =

13
45
-2
MATLAB Matrices

• A matrix can be created in MATLAB as follows (note the


commas AND semicolons):

» matrix = [1 , 2 , 3 ; 4 , 5 ,6 ; 7 , 8 , 9]

matrix =

1 2 3
4 5 6
7 8 9
MATLAB matrices
Generate a “magic square” with equal row/column/diagonal
sums and assign the resulting 3 × 3 matrix to variable a:

>> a= magic(3)
a =
8
3 1 6
4 5 7
9 2

Assignments and subroutine calls normally end with a semicolon.


Without, MATLAB will print each result. Useful for debugging!
Results from functions not called inside an expression are assigned to
the default variable ans.
Type help magic for the manual page of this library function.
MATLAB matrices

Colon generates number sequence: Specify step size with second colon:
>> 11:14 >> 1:3:12
ans = ans =
11 12 13 14 1 4 7 10

>> -1:1 >> 4:-1:1


ans = ans =
0 -1
1 4 3 2 1

>> 3:0 >> 3:-0.5:2


ans = ans =
Empty matrix: 1-by-0 3.0000 2.5000 2.0000
Extracting a Sub-Matrix

• A portion of a matrix can be extracted and stored in a


smaller matrix by specifying the names of both matrices
and the rows and columns to extract. The syntax is:
sub_matrix = matrix ( r1 : r2 , c1 : c2 ) ;
where r1 and r2 specify the beginning and ending rows and
c1 and c2 specify the beginning and ending columns to be
extracted to make the new matrix.
Use [ ] to build new matrices, where , or space as a delimiter
joins submatrices horizontally and ; joins them vertically.
• The elements of this matrix are accessed as follows:
Aij = A(i,j) column j : A(:,j) row i : A(i,:)
MATLAB Matrices
• A column vector can be • Here we extract column 2 of
extracted from a matrix. the matrix and make a column
As an example we create vector:
a matrix below:

» matrix=[1,2,3;4,5,6;7,8,9] » col_two=matrix( : , 2)

col_two =
matrix =
2
1 2 3 5
4 5 6 8
7 8 9
MATLAB Matrices
• A row vector can be • Here we extract row 2 of
extracted from a matrix. the matrix and make a row
As an example we create vector. Note that the 2:2
a matrix below: specifies the second row
and the 1:3 specifies
» matrix=[1,2,3;4,5,6;7,8,9] which columns of the row.

matrix = » rowvec=matrix(2 : 2 , 1 : 3)
1 2 3 rowvec =
4 5 6
7 8 9 4 5 6
Matlab Selection Structures

• An if - elseif - else structure in MATLAB.


Note that elseif is one word.

if expression1 % is true
% execute these commands
elseif expression2 % is true
% execute these commands
else % the default
% execute these commands
end
MATLAB Repetition Structures

• A for loop in MATLAB for x = array


for x = 1: 0.5 : 10
% execute these commands
end

• A while loop in MATLAB while expression


while x <= 10
% execute these commands
end
Scalar - Matrix Addition

» a=3;
» b=[1, 2, 3;4, 5, 6]
b=
1 2 3
4 5 6
» c= b+a % Add a to each element of b
c=
4 5 6
7 8 9
Scalar - Matrix Subtraction

» a=3;
» b=[1, 2, 3;4, 5, 6]
b=
1 2 3
4 5 6
» c = b - a %Subtract a from each element of b
c=
-2 -1 0
1 2 3
Matrix multiplication (dot product)

• • • • • • •
• • • • • • • • • • •
• • • · • • • • = • • • •
• • • • • • • • • • •
• • • • • • •

Each element of the matrix product is the scalar product of


the corresponding row in the first factor and the
corresponding column in the second factor
Review:
Matrix multiplication

• • • •
• • • •
• • • •
·
• • • • • • •
• • • • • • •
• • • = • • • •
• • • • • • •
• • • • • • •

Each element of the matrix product is the scalar product of


the corresponding row in the first factor and the corresponding
column in the second factor
Review:
Matrix multiplication

• • • •
• • • •
• • • •
· k
• • • • • • •
• • • • • • •
• • • • • • •
• • • • • • •
• • • • • • •

Each element of the matrix product is the scalar product of


the corresponding row in the first factor and the corresponding
column in the second factor
Review:
Matrix multiplication

• • • •
• • • •
• • • •
· k
• • • • • • •
• • • • • • •
• • • • • • •
• • • • • • •
• • • • • • •

Each element of the matrix product is the scalar product of


the corresponding row in the first factor and the corresponding
column in the second factor
Review:
Matrix multiplication

• • • •
• • • •
• • • •
· k
• • • • • • •
• • • • • • •
• • • • • • •
• • • • • • •
• • • • • • •

Each element of the matrix product is the scalar product of


the corresponding row in the first factor and the corresponding
column in the second factor
Review:
Matrix multiplication

• • • •
• • • •
• • • •
· k
• • • • • • •
• • • • • • •
• • • • • • •
• • • • • • •
• • • • • • •

Each element of the matrix product is the scalar product of


the corresponding row in the first factor and the corresponding
column in the second factor
Scalar - Matrix Multiplication

» a=3;
» b=[1, 2, 3; 4, 5, 6]
b=
1 2 3
4 5 6
» c = a * b % Multiply each element of b by a
c=
3 6 9
12 15 18
Scalar - Matrix Division

» a=3;
» b=[1, 2, 3; 4, 5, 6]
b=
1 2 3
4 5 6
»c=b/a % Divide each element of b by a
c=
0.3333 0.6667 1.0000
1.3333 1.6667 2.0000
Mathematical Functions

A mathematical function consists of three parts:


input, output and the relationship between the two,
which can be depicted on a graph.
Interpreting a function means converting the symbols
of a formula or a drawn graph into meaningful
information that fits what you're looking for.
When you're interpreting a function, you're answering
questions based on the occasionally cryptic
information available.
Input & Output Commands

MATLAB input & output related Commands:


o disp Displays contents of an array or string.
o fscanf Read formatted data from a file.
o format Controls screen-display format.
o ifprintf Performs formatted writes to screen or file.
o innput Displays prompts and waits for input.
o; Suppresses screen printing.
Mathematical Functions

Logarithms, Polylogarithms, and Zeta Functions


Trigonometric functions
Hyperbolic functions
Complex numbers
Trigonometric, Elliptic and other Integrals

Inbuilt functions:
• sin(x) cos(x) tan(x) exp(x)
• asin(x) acos(x) atan(x) log(x),log10(x)
• sinh(x) cosh(x) tanh(x) sqrt(x) = xˆ(1/2)
• real(x) imag(x) mod(a,b) factorial(n)
Trigonometric functions (Radian)
Trigonometric functions (degree)
Hyperbolic functions
Example:
• hyperbolic functions f(x) = sinh x, f(x) = cosh x and f(x) =
tanh x.
• hyperbolic functions cosh x and sinh x are defined using
the exponential function ⅇ𝑥 .
Complex functions

.
Examples 1:
• Define a function in a file named average.m that accepts
an input vector, calculates the average of the values, and
returns a single result .
Plotting
• Some Commonly used plotting Commands (1)
o axis Sets axis limits.
o fplot Intelligent plotting of functions.
o grid Displays gridlines.
o plot Generates xy plot.
o print Prints plot or saves plot to a file.
o title Puts text at top of plot.
o xlabel Adds text label to x-axis.
o ylabel Adds text label to y-axis.
o axes Creates axes objects.
o close Closes the current plot.
o close all Closes all plots.
o figure Opens a new figure window.
o gtext Enables label placement by mouse.
o hold Freezes current plot.
o legend Legend placement by mouse.
o refresh Redraws current figure window.
o set Specifies properties of objects such as axes.
o subplot Creates plots in sub windows.
o text Places string in figure.
o bar Creates bar chart.
o loglog Creates log-log plot.
o polar Creates polar plot.
o semilogx Creates semi log plot. (logarithmic abscissa).
o semilogy Creates semi log plot. (logarithmic ordinate).
o stairs Creates stairs plot.
o stem Creates stem plot.
• Other Useful MATLAB commands
o who List known variables
o whos List known variables plus their size
o help Ex: >> help sqrt Help on using sqrt
o clear Clear all variables from work space
o clear x y Clear variables x and y from work space
o clc Clear the command window
o what List all m-files in current directory
o dir / ls List all files in current directory
o type test Display test.m in command window
o delete test Delete test.m
o cd a: chdir a: Change directory to a:
o pwd Show current directory
• Reading Data from files
• MATLAB supports reading an entire file and creating a matrix
of the data with one statement.
>> load mydata.dat; % loads file into matrix.
% The matrix may be a scalar, a vector, or a
% matrix with multiple rows and columns. The
% matrix will be named mydata.
>> size (mydata) % size will return the number
% of rows and number of
% columns in the matrix
>> length (myvector) % length will return the total
% no. of elements in myvector
• Plotting with MATLAB (1)

• MATLAB will plot one vector vs. another. The first one will
be treated as the abscissa (or x) vector and the second as
the ordinate (or y) vector. The vectors have to be the
same length.
• MATLAB will also plot a vector vs. its own index. Given a
vector “time” and a vector “dist” we could say:
>> plot (time, dist) % plotting versus time
>> plot (dist) % plotting versus index
• Plotting with MATLAB (2)

• There are commands in MATLAB to "annotate" a plot to


put on axis labels, titles, and legends. For example:
>> % To put a label on the axes we would use:
>> xlabel ('X-axis label')
>> ylabel ('Y-axis label')

>> % To put a title on the plot, we would use:


>> title ('Title of my plot')
• Plotting with MATLAB (3)

• Vectors may be extracted from matrices. Normally, we


wish to plot one column vs. another. If we have a matrix
“mydata” with two columns, we can obtain the columns as
a vectors with the assignments as follows:

>> first_vector = mydata ( : , 1) ; % First column


>> second_vector = mydata ( : , 2) ; % Second one
>>% and we can plot the data
>> plot ( first_vector , second_vector )
Stem vs Plot Vs Stairs
o Both plot and stem functions are used to represent a curve in
MATLAB.
The main difference btwn the 2 is that plot displays the
continuous values for the curve. Think about drawing a graph of
y= sin(x) using a pencil without removing its contact from paper.
Stem displays the discrete values of the points on the curve.
Think about drawing the graph of y=sin(x) for specific values
such as 0,15,30,45,60and 90degrees respectively. Then join
these points from the X-axis. This is the result given by stem.
o Stairs (Y) draws a stairstep plot of the elements of Y.
o When Y is a vector, the x-axis scale ranges from 1 to
size(Y) . When Y is a matrix, the x-axis scale ranges from
1 to the number of rows in Y.
o stairs(X,Y) plots X versus the columns of Y .
Plotting
20-point raised cosine 1
1
real
0.8 imaginary

0.8
0.6

0.6 0.4

0.2
0.4
0

0.2 -0.2

-0.4
0 0 2 4 6 8
0 5 10 15 20 10

x = 0:20; t = 0:0.1:10;
y = 0.5 - 0.5*cos(2*pi * x/20); x = exp(t * (j - 1/3));
stem(x, y); plot(t, real(x), t, imag(x));
title('20-point raised cosine'); grid; legend('real', 'imaginary')

Plotting functions plot, semilogx, semilogy, loglog all expect a pair of


vectors for each curve, with x and y coordinates, respectively.
Use saveas(gcf, 'plot2.eps') to save current figure as graphics file.
2D Plotting
Plotting
Functions and m-files
MATLAB allows writing two kinds of program files:

Scripts - script files are program files with .m extension. In these


files, you write series of commands, which you want to execute
together. Scripts do not accept inputs and do not return any outputs.
They operate on data in the workspace.

Functions - functions files are also program files with .m extension.


Functions can accept inputs and return outputs. Internal variables are
local to the function.
You can use the MATLAB editor or any other text editor to create your
.m files.
Functions and m-files

Only the function that has the same name as the m-file in which it
is defined can be called from outside the file; all other functions
are only visible inside the file. The function keyword sets the
variable whose value will be returned and lists the parameter
variables.
The m-file must be in the current directory (cd) or MATLAB's search
path (path) to become accessible.
Use edit db to edit the m-file, help db to show the first comment lines and
type db to show its source text.
M-files can also contain just sequences of statements instead of a
function definition. These are called simply by typing their name.
Recursion (1)
• Recursion is a repetitive process in which a function calls itself. The
process of repetition can be done in 2 ways using programming:
o Iterative Definition
o Recursive Definition
• Iterative : Repeating a set of statements using loops
• Recursive: A repetitive function is defined recursively whenever
the function appears within the definition itself. E.g. factorial of a no
4! =4x3x2x1; if n is the number then
n!= nx(n-1)x(n-2)x(n-3)x(n-4)……x(n-n)
n!=nx(n-1)!
(n-1)!=(n-1) x (n-2)!
(n-2)!=(n-2)x(n-3)!
……………………………………
(n-n)!=1 (0!, 1! =1)
Recursion (2)
• The recursive function has two elements : each call either
solves one part of the problem or it reduces the size of the
problem. The statement that solves the problem is known as
the base case. The rest of the function is known as the
general case. Each recursive function must have a base
case.
n=nx(n-1)! Is the general case as it is valid for all n values
n!=1 is considered as base case
• Base case: factorial(0)
• General case: nxfactorial(n-1).
Recursion (3)
• The following are the rules for designing a recursive function:
1. First, determine the base case
2. Then, determine the general case
3. Finally, combine the base case and general case into a function
• Matlab Syntax:
f = factorial(n) e.g. f = factorial(10) ; f=3628800
Factorial of an Array elements:
n = [0 1 2; 3 4 5]; f = factorial(n)
f = 2×3
1 1 2
6 24 120
Iterations (1)
• We can use iterations to get the multiplication of numbers
n=9
% use iterations
f = 1;
for i = 1:n
f = f*i;
end
f
Also
n=input('the value of n: ');
f=1;
for i=1:n
f=f*i;
end
disp('factorial is')
disp(f)

You might also like