# Programming in MATLAB lecture two by Jskc23

VIEWS: 16 PAGES: 23

• pg 1
```									PROGRAMMING IN
MATLAB

AM2032 JAYANTA MUKHERJEE
Vectorization
• 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 y=sin(), is a vectorized statement as opposed to
y1=sin(1),y2=sin(  2), …e.t.c.
AM2032 JAYANTA MUKHERJEE
Loops and Iterations
The for loop…
• Similar to other       N=10;
programming            for I = 1:N
languages                for J = 1:N
• Repeats loop a set         A(I,J) = 1/(I+J-1);
number of times          end
(based on index)       end
• Can be nested

AM2032 JAYANTA MUKHERJEE
Loops and Iterations-cont.
The while loop…
I=1; N=10;
• Similar to other         while I<=N
programming                 J=1;
languages                   while J<=N
A(I,J)=1/(I+J-1);
• Repeats loop until            J=J+1;
logical condition           end
returns FALSE.              I=I+1;
• Can be nested.           end

AM2032 JAYANTA MUKHERJEE
Conditional Statements
if, elseif and else statements…..
•   Works on                  if I == J
Conditional                 A(I,J) = 2;
statements                elseif abs(I-J) == 1
•   Short-circuited in          A(I,J) = -1;
else
MATLAB - once a
condition is true, the      A(I,J) = 0;
sequence terminates.      end

AM2032 JAYANTA MUKHERJEE
IN MATLAB
Calculations are greatly speeded up by using vectorized operations
rather than using a loop for iteration:

Example (1):            Clears variables and functions from memory
>> % Fill b with square roots of 1 to 1000 using a for loop.
>> clear;
>> tic;               Starts a stop watch timer
>> for i=1:1000
b(i)=sqrt(i);
end
>> t=toc;                     Stops the timer
>> disp(['Time taken for for loop method is',num2str(t)]);
Time taken for for loop method is 0.0033462

AM2032 JAYANTA MUKHERJEE
IN MATLAB-cont.
Example (2):
Clears variables and functions from memory

>> % Fill b with square roots of 1 to 1000 using a for loop.
>> clear;
>> tic;              Starts a stop watch timer
>> a=1:1:1000;
b=sqrt(a);
>> t=toc;                    Stops the timer
>> disp(['Time taken for for loop method is',num2str(t)]);
Time taken for for loop method is 0.0010155

AM2032 JAYANTA MUKHERJEE
A 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.
AM2032 JAYANTA MUKHERJEE
SCRIPT Example
Let us write a script to solve the following system of linear equations, and save it as
solvex.m
>>r=1                     % You need to specify the value of the variable r in workspace
5    2r      r       x1           2
>> solvex                 % This executes the script file named solvex
A*X=B
3    6 2r-1          x2     =     3
det_A=
2 r-1       3r       x3           5
64
This is the out put. The values of the
x=                                 which solves the avobe equation an calculates det(A) as well
% This is a script file „solvex.m‟ variables det_A and X appear on the
A=[5 2*r r; 3 6 2*r-1; 2 r-1 3*r];screen as there was ano semicolon at
-0.0312                                         % Create matrix A
B=[2;3;5];                                         % corresponding
the end of the |Create a vector B line in
0.2344                         the script file. find the determinant, notice no semicolon
det_A=det(A)                                       %
1.6875
X=A\B                                              % find X, notice the backslash

A\B is same as A-1B, but is computationally more stable !
AM2032 JAYANTA MUKHERJEE
RUNNING A SCRIPT FILE

Run the program by selecting the “run” button

AM2032 JAYANTA MUKHERJEE
Function 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.

AM2032 JAYANTA MUKHERJEE
Function Files in MATLAB-2
A function definition line may look slightly different depending on
The syntax is a output, definition line is as follows……
weather therefor nofunction single output, or multiple outputs.
function [output variables] = function_name (input variables);
Examples:
The function_name must be the same as the filename
(without the .m Line                                   is written.
Function Definitionextension) in which the functionFile name
For example if the name of the function is euler then it must
function [rho, H, F] = motion (x, y, t);                 motion.m
file with the definition line,
be written and saved in a the function name euler.m function, must
CAUTION: The first word in
befunction [theta] = angleTH (x, y);mistake is to type itangleTH.m
typed in lower case. A common                           as Function
function theta = THETA (x, y, z);                      THETA.m
function [] = circle (r);                              circle.m
function circle (r)                                    circle.m
AM2032 JAYANTA MUKHERJEE
ANATOMY OF A FUNCTION FILE
Function definition            Output list        Function
line                                        name           Input list

function [xout, yout] = function_name (input variables);
H1 line        % add 1 line description of the function here
line used by
% include your name and date
x = blah;
Body of         .
line can be accessed
the
.                                    by the lookfor
function
y = more_blah;                          command
AM2032 JAYANTA MUKHERJEE
SAVING A FUNCTION
FILE:IMPORTANT

The function name must be the same as the
filename

AM2032 JAYANTA MUKHERJEE
Executing 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.

(1) 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:              Input variables are
Input variables must be
function [rho, H, F] = motion (x, y, t);      already specified
specified before hand
then all the following commands represent legal call (execution)
statements:
[r, h, f] =motion (rx, 3.5,(xt, yt, time);
[r, h, f] motion (2, ry, 0.001);
[r, angmom,=force] = motion [0:100]);
AM2032 JAYANTA MUKHERJEE
Executing 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.

AM2032 JAYANTA MUKHERJEE
Sub-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

AM2032 JAYANTA MUKHERJEE
Example: Sub-functions

function [totalsum,average] = subfunc (input_vector)
Primary    % SUBFUNC Calculates cumulative total & average
Function   totalsum = sum(input_vector);
average = ourmean(input_vector);%Call to subfunction

function y = ourmean(x)
% (OURMEAN) Calculates average
[m,n] = size(x);
Sub-        if m == 1
Function      m = n;
end
y = sum(x)/m;

AM2032 JAYANTA MUKHERJEE
Debugging (Visual)

Select
Workspace

Set Auto-
Breakpoints

Set Breakpoint
Clear Breaks
Step In
Single Step
Continue
Quit Debugging

AM2032 JAYANTA MUKHERJEE
Miscellaneous Stuff
• MATLAB supports reading an entire file and creating a
matrix of the data with one statement.

• The matrix may be a scalar, a vector, or a matrix with
multiple rows and columns. The matrix will be named
my_data.
>> size (my_data)
% size will return the number of rows and number of columns in
the matrix
>> length (my_data)
% length will return the total no. of elements in my_data
AM2032 JAYANTA MUKHERJEE
TIPS
• Use Pseudo Codes, Flow charts etc to chalk out a

• 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.
AM2032 JAYANTA MUKHERJEE
Lab Sessions
• Monday 2PM
• Tuesday 3PM                    Starting Next Monday
• Wednesday 12PM

This is how it was done last year. If anybody
has any suggestion regarding the time and
There will be three groups with 30 students
(approx) each divided alphabetically
according to their names.
AM2032 JAYANTA MUKHERJEE