Sie sind auf Seite 1von 14

Introduction to Matlab 4

Matlab Programming

Omed Ghareb Abdullah


Sulaimani University
College of Sciences
Physics Department

What are we interested in?


y Matlab is too broad for our purposes in this course.
y The features we are going to require is

Series of Matlab
Matlab
commands
m-files Command Line mat-files

functions Command Data


Input execution like DOS storage/
Output command window loading
capability
p y
2

1
M‐Files: 
Scripts and Functions
y You can create and save code in text files (called 
m‐files since the ending must be .m)
y M‐file is an ASCII text file similar to FORTRAN or 
C source codes ( computer programs)
y A script can be executed by typing the file name, 
or using the “run” command
h “ ” d

M‐Files: 
Scripts and Functions
This section covers the following topics regarding
functions:

1. M-File Scripts.
2. M-File Functions

Difference between scripts and functions


Scripts share variables with the main workspace
Functions do not
4

2
Script Files
¾ Scripts are the simplest kind of M-file because they have no
input or output arguments. They are useful for automating
series of MATLAB commands,
commands such as computations that you
have to perform repeatedly from the command line.

¾ Scripts share the base workspace with your interactive


MATLAB session and with other scripts. They operate on
existing data in the workspace, or they can create new data on
which to operate.
p Anyy variables that scripts
p create remain in the
workspace after the script finishes so you can use them for
further computations. You should be aware, though, that
running a script can unintentionally overwrite data stored in the
base workspace by commands entered at the MATLAB
command prompt.
5

Script Files
¾ Script file – a series of MATLAB commands 
saved on a file, can be executed by
‰ typing the file name in the Command Window
‰ invoking the menu selections in the Edit Window: 
Debug, Run

¾ Create a script file using menu selection:
File, New, M-file

3
Simple Script Example
p MTLAB p
Write a simple g
program g
to evaluate the following
function for any value of x:

y = x + 4x − 5 2

These statements are written in m‐file 
and saved under name prog1.m
% M-file script to evaluate y % Comment lines
% for any value of x % x is a variable
x = input ('Enter the value of x : '); % semicolon at the
% ; is used to suppress the data from duplicate on the output
y = x ^ 2 + 4 * x – 5;
disp(y) % Display the result

4
The output will be as the following.. 
In command window :
>> prog1
Enter the value of x: 3
16

>>

Function File
¾ Functions are program routines, usually implemented in M-
files, that accept input arguments and return output arguments.
Theyy operate
p on variables within their own workspace.
p This
workspace is separate from the workspace you access at the
MATLAB command prompt.
¾ Each M-file function has an area of memory, separate from the
MATLAB base workspace, in which it operates. This area,
called the function workspace, gives each function its own
workspace context.
¾ While using MATLAB, the only variables you can access are
th
those i the
in th calling
lli context,
t t be
b it the
th base
b workspace
k or that
th t off
another function. The variables that you pass to a function must
be in the calling context, and the function returns its output
arguments to the calling workspace context. You can, however,
define variables as global variables explicitly, allowing more
than one workspace context to access them
10

5
Function File
y Function file: M‐file that starts with the word 
function
y Function can accept input arguments and 
return outputs 
y Analogous to user‐defined functions in 
programming languages such as Fortran, C, …
y Save the function file as function_name.m
y User helpp function in command window for 
additional information

input Function output

11

Simple Function Example
Write a simple MTLAB program to evaluate the following
function for any value of x:

y = x + 4x − 5 2

12

6
In M – File write the following 
statements and save the file as function 
name prog2 2

function y=prog2(x)
% function name must be the same name of the m-file
y=x^2 + 4 * x - 5 ;

13

This function  will be run as the 
following
>> prog2(5)

ans =

40
>>

14

7
Problem 1
Write a Script m‐files in Matlab to calculate a factorial of a 
number factscript.m
%factscript- compute n-factorial, n!=1*2*...*n
y = prod(1:n)

Executed by typing its name


>> factscript
Operates on variables in global workspace
ƒ Variable n must exist in workspace
ƒ Variable y is created (or over-written)
Use comment lines (starting with %) to document file!

15

Displaying code and getting help
y To list code, use type command
y >> type factscript

y The help command displays first consecutive comment 
lines
y >> help factscript

y=prod(1:n);
disp([num2str(n),’!= ‘,num2str(y)])

Number to string conversion


16

8
Problem 2
Write a function m‐file in MATLAB to calculate a factorial 
of a number

function[output-arguments]=function-name(input-arguments)
% Comment lines
<function body>
fact.m
function [z]
[z]=fact(n)
fact(n)
% fact- compute factorial
% z=fact(n)

>> y=fact(10) z = prod(1:n);

>> y=prod(1:10)
17

Modifing  fact.m function
fact.m
function y=fact(n)
% FACT – Display factorials of integers 1..n
if n < 0
error(’Input must be non-negative’)
elseif abs(n-round(n)) > 0
error(’Input must be an integer’)
end
for
f k=1:n
k 1
kfac=prod(1:k);
disp([num2str(k),’!= ’,num2str(kfac)])
y(k)=kfac;
end;
18

9
Scripts or function: when used?
y Functions
y Take inputs, generate outputs, have internal variables 
Take inputs  generate outputs  have internal variables 
y Solve general problem for arbitrary parameters
y Scripts
y Operate on global workspace
y Document work, design experiment or test 
y Solve a very specific problem once 
facttest.m
% facttest- test factfun
n=50;
y=fact(n)
Z=prod(1:n) 19

Problem 3
y Write a faction to calculate a mean and standard 
deviation of a vector.
function [mean, stdev] = stats(x)
% calculate the mean and standard deviation of a vector x
n = length(x);
mean = sum(x)/n;
stdev = sqrt(sum((x-mean).^2/(n-1)));

>> x=[1.5 3.7 5.4 2.6 0.9 2.8 5.2 4.9 6.3 3.5];
>> [m,s] = stats(x)
m =
3.6800
s =
1.7662

y Function M‐file can return more than one result
20

10
Problem 4
y Find the cube of a number ‐> (x3)
function [y] = cube(x) >> z=cube(4)
% Put some text here 64

y = x*x*x;

y Find the cube of two numbers
>>[a b]=cube(2,3)
function [y1, y2] = cube(x1, x2) a=8
% Put some text here b = 27
>>y=cube(3)
y1 = x1*x1*x1;
???
y2 = x2*x2*x2;
21

nargin
y Matlab will accept a function call with any number of 
inputs and outputs
y nargin
i can be used to find out how many inputs the user 
 b   d   fi d   h    i  h    
has provided
function [y1, y2] = cube(x1, x2)
if nargin == 1 >> [a b] = cube(2,3)
y1 = x1*x1*x1; a=8
y2 = NaN; b = 27
elseif nargin == 2
>> y=cube(3)
y1 = x1*x1*x1;
y= 27
y2 = x2*x2*x2;
end
nargin: Number of function input arguments. 22

11
return
y return terminates computation of the function and 
returns whatever is calculated thus far
function [y1, y2] = cube(x1, x2)
>> [a b] = cube(2,3)
if nargin == 1
a=8
y1 = x1*x1*x1;
b = 27
y2 = NaN;
>> y=cube(3)
return
y= 27
end
y1 = x1*x1*x1;
y2 = x2*x2*x2;

23

Problem 5
y Write a script that asks for a temperature (in degrees 
Fahrenheit) 
y computes the equivalent temperature in degrees 
Celsius. 
y The script should keep running until no number is 
provided to convert. 
y use isempty

TC =
5
(TF − 32)
9
24

12
Solution
while 1 % use of an infinite loopp
TinF = input('Temperature in F: '); % get input
if isempty(TinF) % how to get out
break
end
TinC = 5*(TinF - 32)/9; % conversion
disp(' ')
disp([' ==> Temperature in C = ',num2str(TinC)])
disp(' ')
end
25

Problem 6
y Write a function that asks for a temperature (in 
degrees Fahrenheit) 
y computes the equivalent temperature in degrees 
Celsius. 
y The function should give an error massage in case no 
number is provided to convert. 
y use nargin.

TC =
5
(TF − 32)
9
26

13
Solution
function TinC=temp2(TinF)
if nargin==0 % if there is no input
disp('no temparture was entered');
TinC=NaN;
else
TinC = 5*(TinF - 32)/9; % conversion
disp([' ==> Temperature in C = ',num2str(TinC)])
disp([ ,num2str(TinC)]) ;
end >> temp2(44);
==> Temperature in C = 6.6667
>> temp2;
no temparture was entered
>> 27

14