Download matlab - NUS Physics Department

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Big O notation wikipedia , lookup

Functional decomposition wikipedia , lookup

Continuous function wikipedia , lookup

Elementary mathematics wikipedia , lookup

Non-standard calculus wikipedia , lookup

Dirac delta function wikipedia , lookup

Function (mathematics) wikipedia , lookup

Function of several real variables wikipedia , lookup

History of the function concept wikipedia , lookup

Transcript
MATLAB
Lecture Two (Part I)
Thursday, 3 July 2003
Chapter 4
Programming in MATLAB
M-Files


Script file: a collection of
MATLAB commands
Function file: a definition file for
one function
Script Files


Any valid sequence of MATLAB
commands can be in the script
files.
Variables defined/used in script
files are global, i.e., they
present in the workspace.
Script File Example

Linear equation with a
parameter r - solve the
equation
5 x + 2r y + r z = 2,
3 x + 6 y + (2r-1) z = 3,
2 x + (r-1) y + 3r z = 5.
Script File Example
% ---This is the script file `solvex.m'
% It solves equation (4.1) for x and also
% calculate det(A).
A = [5 2*r r; 3 6 2*r-1; 2 r-1 3*r];
b = [2; 3; 5];
det_A = det(A)
x = A\b
Script Files: Caution


Never name a script file the
same as the name of a variable
it computes.
The name of a script file must
begin with a letter, followed by
letters, digits, or underscores,
with up to 19 character long,
with extension .m.
Script Files: Caution


All variables generated by a
script file are left in the
workspace. Avoid name
clashes with built-in functions.
Use the command exist('name')
to check if the name exists.
Function Files


A function file is also an M-file,
except that the variables in a
function file are all local.
Function file is like a subroutine
in FORTRAN, procedure in
Pascal, or function in C.
Syntax of Function
Definition
Function [output variables] =
functionname(input variables);
E.g.,
function [rho,H,F] = motion(x,y,z);
function [theta] = angleTH(x,y);
function theta = THETA(x,y,z);
function [ ] = circle( r );
function circle( r );
Some comments on
function definition


Unlike other programming
languages, data types are not
specified in argument list and
return values.
MATLAB functions can return a
list of values (a vector).
Function M-file


The name of the function M-file
must be the same as the name
of the function (case sensitive).
E.g.,
function theta = THETA(x,y)
file name should be THETA.m
Anatomy of
a Function File
function [xout, yout] = funcname(xin, yin);
% FUNCNAME : compute …
% write on-line help comment
% include your name and date
x = blah;
y = moreblah;
xout = …,
yout = ...
Executing of a Function



If the function is defined by
function [rho,H,F] = motion(x,y,t);
The function can be called (used)
as
[r, ang, force] = motion(xt,yt,time);
Or
motion(2, 3.5, 0.001);
Function as Argument


The name of the function is
passed as a string, quoted with
single quotes.
E.g.,
integration('sin', 0, 1.0)
Function as Argument



feval evaluates a function
whose name is specified as a
string (e.g. passed by argument
list)
E.g.,
feval('sin', 0.3)
is the same as sin(0.3)
Integration Example

Function definition
function res = integration(f,a,b)
… feval(f, x);
…

Use
integration('sin', 0, 1)
Language-Specific
Features


Use of comments to create online help, H1 line
Line continuation, use … at the
end of a line
Global Variable in
Function
Function xdot = ode1(t,x);
% ODE1 : function to …
global k_value c_value
xdot = k_value + ...
Loops, branches,
control-flow
branches
loop
flow
For Loop
for m=1:100
y(m) = sin(1.0/m);
end
for n=100:-2:0, k=…, end
n runs over 100, 98, 96, …, 2, 0.
While Loop
num = 0; v = 1; i = 1;
while num < 10
num = num + 1;
v = v * 2^num;
…
end
IF-Elseif-Else
if i > 5
k = i;
elseif (i>1) & (j==20)
k = 5*i + j;
else
k = 1;
end
Switch-Case-Otherwise
switch flag
case value1
block1
case value 2
block2
…
otherwise
blockdefault
end
Switch-Case-Otherwise
switch color
case 'red'
c = [1 0 0];
case 'green'
c = [0 1 0];
case 'blue'
c = [0 0 1];
otherwise
error('invalid choice')
end
Break


The command `break' inside a
for or while loop terminates the
execution of the loop.
Unlike C/C++, no need to put
break in the switch statement.
Return
function animatebar(t0, tf, x0);
% ANIMATEBAR do such and ...
disp('Do you want to see …')
ans = input('Enter 1 if yes, 0 if No');
if ans==0
return
else
plot(x, …)
end
Interactive Input


Input('string') print the 'string'
and wait for user input
E.g.
n = input('Enter a number n:');
more = input('More simulation?
'Y/N', 's');
The input will be a string
Keyboard



The commend `keyboard' return
control to the keyboard from
script or function.
Type `return' makes control
back to the script or function.
Useful for debugging.
Menu

coord = menu('Menu Name', 'A',
'B', 'C');
creates a menu choice with
name `Menu Name', and three
buttons labeled `A', `B', and `C'.
The return value coord is 1 for
choice A, 2 for B, and 3 for C.
C style I/O
MATLAB supports many standard
C-language file and I/O functions.
fopen
opens a file
fclose
closes a file
fscanf
reads formatted data
fprintf
writes formatted data
fgets
reads a line

Advanced Data Objects

Multidimensional array
• e.g. A(4,4,2)

Structure
• fallsem.couse = 'cs101';
• fallsem.prof = 'Turing';
• fallsem.score = [80 75 95];

Cells
• C = {0.1 's' fallsem};
Exercise 1

Define a function that (1) ask
the user to enter a sequence of
numbers, (2) sort the numbers
in ascending order, (3) return
the sorted numbers.
How to Submit

Send your diary file and *m file
by email to Nguyen Ngoc Son
[email protected]