Title: PROGRAMMING IN MATLAB
1PROGRAMMING IN MATLAB
2Vectorization
- All the built in MATLAB functions are optimized
for vector operations. Consequently vectorized
commands or codes run much faster in MATLAB - Vectorization refers to a manner of computation
in which an operation is performed simultaneously
on a list of numbers (a vector /array) rather
than sequentially on each number of the list. - For example, let be a list of 100
numbers.Then the statement ysin( ), is a
vectorized statement as opposed to y1sin(
1),y2sin( 2), e.t.c.
3Loops and Iterations
The for loop
- Similar to other programming languages
- Repeats loop a set number of times (based on
index) - Can be nested
- N10
- for I 1N
- for J 1N
- A(I,J) 1/(IJ-1)
- end
- end
4Loops and Iterations-cont.
The while loop
- I1 N10
- while IltN
- J1
- while JltN
- A(I,J)1/(IJ-1)
- JJ1
- end
- II1
- end
- Similar to other programming languages
- Repeats loop until logical condition returns
FALSE. - Can be nested.
5Conditional Statements
if, elseif and else statements..
if I J A(I,J) 2 elseif abs(I-J)
1 A(I,J) -1 else A(I,J) 0 end
- Works on Conditional statements
- Short-circuited in MATLAB - once a condition is
true, the sequence terminates.
6SOMETHINGS ABOUT LOOPS IN MATLAB
Calculations are greatly speeded up by using
vectorized operations rather than using a loop
for iteration
Clears variables and functions from memory
Example (1)
gtgt Fill b with square roots of 1 to 1000 using
a for loop. gtgt clear gtgt tic gtgt for i11000
b(i)sqrt(i) end gtgt ttoc gtgt disp('Time
taken for for loop method is',num2str(t)) Time
taken for for loop method is 0.0033462
Starts a stop watch timer
Stops the timer
7SOMETHINGS ABOUT LOOPS IN MATLAB-cont.
Example (2)
Clears variables and functions from memory
gtgt Fill b with square roots of 1 to 1000 using
a for loop. gtgt clear gtgt tic gtgt a111000
bsqrt(a) gtgt ttoc gtgt disp('Time taken for for
loop method is',num2str(t)) Time taken for for
loop method is 0.0010155
Starts a stop watch timer
Stops the timer
8A MATLAB SCRIPT FILE
- A script file is an M-file with a set of MATLAB
commands in it. - A script file may contain any number of commands,
including those that call the built in functions
or functions written by you. - The MATLAB editor is used to write the scripts.
Press F5 to run your script. - Never name your script the same as the name of a
variable it computes otherwise MATLAB will have
problems accessing the file. - Avoid writing anything in your script that
clashes with built-in functions. - Save your script as a m-file. Save it always in
the WORK directory/folder .Otherwise MATLAB
will have problems in accessing that file. - Avoid any space between the letters or numbers
when you name your m-file. MATLAB doesn't like it
and will create unnecessary problems.
9SCRIPT Example
Let us write a script to solve the following
system of linear equations, and save it as
solvex.m
gtgtr1 You need to
specify the value of the variable r in
workspace gtgt solvex This
executes the script file named solvex det_A
64 x -0.0312 0.2344 1.6875
x1 x2 x3
2 3 5
AXB
This is the out put. The values of the variables
det_A and X appear on the screen as there was no
semicolon at the end of the corresponding line in
the script file.
This is a script file solvex.m which solves
the avobe equation an calculates det(A) as
well A5 2r r 3 6 2r-1 2 r-1 3r
Create a matrix A B235
Create a vector B det_Adet(A)
find the determinant, notice no semicolon XA\B
find X, notice the backslash
A\B is same as A-1B, but is computationally more
stable !
10RUNNING A SCRIPT FILE
11Function Files in MATLAB-1
- A function file is also an m-file, like a script
file. - Function files are like programs or subroutines
in FORTRAN, procedures in PASCAL and functions in
C or C. - Once you get to know MATLAB well this is where
you are likely to spend most of your time - writing and refining your own function files.
- A function file begins with a function definition
line, which has a well defined list of inputs and
outputs. Without this line the file becomes a
script file.
12Function Files in MATLAB-2
A function definition line may look slightly
different depending on weather there is no
output, single output, or multiple outputs.
The syntax for a function definition line is as
follows
function output variables function_name
(input variables)
Examples Function Definition Line
File name function
rho, H, F motion (x, y, t)
motion.m function theta angleTH (x, y)
angleTH.m function
theta THETA (x, y, z)
THETA.m function circle (r)
circle.m function circle (r)
circle.m
The function_name must be the same as the
filename (without the .m extension) in which the
function is written. For example if the name of
the function is euler then it must be written and
saved in a file with the name euler.m
CAUTION The first word in the function
definition line, function, must be typed in lower
case. A common mistake is to type it as Function
13ANATOMY OF A FUNCTION FILE
Function definition line
Function name
Output list
Input list
function xout, yout function_name (input
variables) add 1 line description of the
function here write online help comments
here include your name and date x blah . . y
more_blah
H1 line
Comment line used by online help
Comments in the H1 line can be accessed by the
lookfor command
Body of the function
14SAVING A FUNCTION FILEIMPORTANT
The function name must be the same as the filename
15Executing a Function
- There are two ways in which a function can
be executed, weather it is in built or user
written. - (1)With explicit output, (2) Without any
output. - With explicit output This is the full syntax of
calling a function. Both the output and the input
list are specified in the call. Example if the
function reads - function rho, H, F motion (x, y, t)
- then all the following commands represent
legal call (execution) statements
Input variables must be specified before hand
Input variables are already specified
r, h, f motion (rx, ry, 0100)
r, h, f motion (2, 3.5, 0.001)
r, angmom, force motion (xt, yt, time)
16Executing a Function-cont.
(2) Without any output
The output list can be omitted entirely if the
computed quantities are not of immediate
interest. This might be the case when the
function displays the desired result graphically.
17Sub-functions
- Allows more than one function to be within the
same M-file (modularize code) - M-file must have the name of the first (primary)
function - Sub-functions can only be called from within the
same M-file - Each sub-function has its own workspace
18Example Sub-functions
function totalsum,average subfunc
(input_vector) SUBFUNC Calculates cumulative
total average totalsum sum(input_vector) aver
age ourmean(input_vector)Call to
subfunction function y ourmean(x)
(OURMEAN) Calculates average m,n size(x)
if m 1 m n end y sum(x)/m
Primary Function
Sub- Function
19Debugging (Visual)
Select Workspace Set Auto- Breakpoints
Set Breakpoint Clear Breaks Step In Single
Step Continue Quit Debugging
20Miscellaneous Stuff
Reading Data from files
- MATLAB supports reading an entire file and
creating a matrix of the data with one statement. - gtgt load my_data.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 my_data. - gtgt size (my_data)
- size will return the number of rows and number
of columns in the matrix - gtgt length (my_data)
- length will return the total no. of elements
in my_data
21TIPS
- Use Pseudo Codes, Flow charts etc to chalk out a
plan for your code. - Keep your functions modular, that is break big
computations into chunks and write separate
functions for them. Also try to keep the length
of functions small. - Make it a habit of writing comments. Its always
useful.
22Lab Sessions
- Monday 2PM
- Tuesday 3PM
- Wednesday 12PM
- This is how it was done last year. If anybody
has any suggestion regarding the time and days
please let me know. - There will be three groups with 30 students
(approx) each divided alphabetically according to
their names.
Starting Next Monday
23Next Lecture We start with numerical Techniques.
Lecture notes can be found at the following
link http//euclid.ucc.ie/framesets/fset_staffdir
ectory.htm
Then click on my name and then on Lecture Notes
Save the lecture notes in your PC at is wont open
on your internet browser. Once saved it opens as
read only, (as it is password protected).