04 matlab programming
DESCRIPTION
Lecture (4): Matlab Programming - Sulaimani University - College of Science - Physics DepartmentTRANSCRIPT
1
Matlab Programming
Introduction to Matlab 4
Omed Ghareb AbdullahSulaimani UniversitySulaimani UniversityCollege of SciencesCollege of SciencesPhysics DepartmentPhysics Department
1
What are we interested in?Matlab is too broad for our purposes in this course.The features we are going to require isThe features we are going to require is
Matlab
Command Linem-files mat-files
Series of Matlab
commands
functions Command execution like DOS command window
p y
Input Output
capability
Data storage/ loading
2
2
M‐Files: Scripts and Functions
You can create and save code in text files (called m‐files since the ending must be .m)M‐file is an ASCII text file similar to FORTRAN or C source codes ( computer programs)A script can be executed by typing the file name,
h “ ” dor using the “run” command
3
M‐Files: Scripts and Functions
This section covers the following topics regardingfunctions:
1. M-File Scripts.2. M-File Functions
Difference between scripts and functionsDifference between scripts and functions
Scripts share variables with the main workspace
Functions do not4
3
Scripts are the simplest kind of M-file because they have noinput or output arguments. They are useful for automatingseries of MATLAB commands such as computations that you
Script Files
series of MATLAB commands, such as computations that youhave to perform repeatedly from the command line.
Scripts share the base workspace with your interactiveMATLAB session and with other scripts. They operate onexisting data in the workspace, or they can create new data onwhich to operate. Any variables that scripts create remain in thep y pworkspace after the script finishes so you can use them forfurther computations. You should be aware, though, thatrunning a script can unintentionally overwrite data stored in thebase workspace by commands entered at the MATLABcommand prompt.
5
Script FilesScript file – a series of MATLAB commands saved on a file, can be executed bytyping the file name in the Command Windowinvoking the menu selections in the Edit Window: Debug, Run
Create a script file using menu selection:File, New, M-file
6
4
Simple Script Example
Write a simple MTLAB program to evaluate the following
542 −+= xxy
p p g gfunction for any value of x:
7
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; y x 2 + 4 x 5;
disp(y) % Display the result
8
5
The output will be as the following.. In command window :
>> prog1Enter the value of x: 3
16
>>
9
Functions are program routines, usually implemented in M-files, that accept input arguments and return output arguments. They operate on variables within their own workspace. This
Function File
y p pworkspace is separate from the workspace you access at the MATLAB command prompt. Each M-file function has an area of memory, separate from theMATLAB base workspace, in which it operates. This area,called the function workspace, gives each function its ownworkspace context.While using MATLAB, the only variables you can access areth i th lli t t b it th b k th t fthose in the calling context, be it the base workspace or that ofanother function. The variables that you pass to a function mustbe in the calling context, and the function returns its outputarguments to the calling workspace context. You can, however,define variables as global variables explicitly, allowing morethan one workspace context to access them
10
6
Function FileFunction file: M‐file that starts with the word functionFunction can accept input arguments and return outputs Analogous to user‐defined functions in programming languages such as Fortran, C, …Save the function file as function_name.mUser help function in command window for padditional information
Function outputinput
11
Simple Function Example
Write a simple MTLAB program to evaluate the following function for any value of x:
542 −+= xxy
12
7
In M – File write the following statements and save the file as function
2
function y=prog2(x) % function name must be the same name of the m-file
y=x^2 + 4 * x - 5 ;
name prog2
13
This function will be run as the following
>> prog2(5)
ans =
40>>>>
14
8
Write a Script m‐files in Matlab to calculate a factorial of a number
Problem 1
number
%factscript- compute n-factorial, n!=1*2*...*n
y = prod(1:n)
factscript.m
Executed by typing its name>> factscript
Operates on variables in global workspace
Variable n must exist in workspaceVariable y is created (or over-written)
Use comment lines (starting with %) to document file!
15
Displaying code and getting helpTo list code, use type command>> type factscript
The help command displays first consecutive comment lines>> help factscript
y=prod(1:n);disp([num2str(n),’!= ‘,num2str(y)])
Number to string conversion16
9
Problem 2Write a function m‐file in MATLAB to calculate a factorial of a number
function[output-arguments]=function-name(input-arguments)
% Comment lines
<function body>
function [z]=fact(n)
fact.m
of a number
function [z] fact(n)% fact- compute factorial% z=fact(n)
z = prod(1:n);>> y=fact(10)
>> y=prod(1:10)
17
Modifing fact.m functionfunction y=fact(n)% FACT – Display factorials of integers 1..n
fact.m
if n < 0
error(’Input must be non-negative’)
elseif abs(n-round(n)) > 0
error(’Input must be an integer’)
end
f k 1for k=1:n
kfac=prod(1:k);
disp([num2str(k),’!= ’,num2str(kfac)])
y(k)=kfac;
end;18
10
Scripts or function: when used?Functions
Take inputs generate outputs have internal variables Take inputs, generate outputs, have internal variables Solve general problem for arbitrary parameters
ScriptsOperate on global workspaceDocument work, design experiment or test Solve a very specific problem once Solve a very specific problem once
% facttest- test factfun
n=50;y=fact(n)
Z=prod(1:n)
facttest.m
19
Write a faction to calculate a mean and standard deviation of a vector.
Problem 3
function [mean, stdev] = stats(x)
% calculate the mean and standard deviation of a vector xn = 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.6800s =
1.7662
Function M‐file can return more than one result20
11
Find the cube of a number ‐> (x3)function [y] = cube(x) >> z=cube(4)
Problem 4
function [y] cube(x)
% Put some text here
y = x*x*x;
>> z=cube(4)
64
Find the cube of two numbers>>[a b]=cube(2,3)
function [y1, y2] = cube(x1, x2)
% Put some text here
y1 = x1*x1*x1;
y2 = x2*x2*x2;
a = 8
b = 27
>>y=cube(3)
???
21
narginMatlab will accept a function call with any number of inputs and outputs
i b d fi d h i h nargin can be used to find out how many inputs the user has provided
function [y1, y2] = cube(x1, x2)
if nargin == 1
y1 = x1*x1*x1;
y2 = NaN;
>> [a b] = cube(2,3)
a = 8
b 27y2 = NaN;
elseif nargin == 2
y1 = x1*x1*x1;
y2 = x2*x2*x2;
end
b = 27
>> y=cube(3)
y= 27
nargin: Number of function input arguments. 22
12
returnreturn terminates computation of the function and returns whatever is calculated thus far
function [y1, y2] = cube(x1, x2)
if nargin == 1
y1 = x1*x1*x1;
y2 = NaN;
return
>> [a b] = cube(2,3)
a = 8
b = 27
>> y=cube(3)return
end
y1 = x1*x1*x1;
y2 = x2*x2*x2;
y= 27
23
Write a script that asks for a temperature (in degrees
Problem 5Write a script that asks for a temperature (in degrees Fahrenheit) computes the equivalent temperature in degrees Celsius. The script should keep running until no number is provided to convert. use isempty
( )3295
−= FC TT
24
13
Solutionwhile 1 % use of an infinite loopp
TinF = input('Temperature in F: '); % get inputif isempty(TinF) % how to get out
breakend TinC = 5*(TinF - 32)/9; % conversiondisp(' ')disp([' ==> Temperature in C = ',num2str(TinC)]) disp(' ')
end25
Write a function that asks for a temperature (in
Problem 6Write a function that asks for a temperature (in degrees Fahrenheit) computes the equivalent temperature in degrees Celsius. The function should give an error massage in case no number is provided to convert. use nargin.
( )3295
−= FC TT
26
14
Solutionfunction TinC=temp2(TinF)
if nargin==0 % if there is no inputif nargin==0 % if there is no inputdisp('no temparture was entered');TinC=NaN;elseTinC = 5*(TinF - 32)/9; % conversiondisp([' ==> Temperature in C = ',num2str(TinC)]) ;disp([ Temperature in C ,num2str(TinC)]) ;
end >> temp2(44);
==> Temperature in C = 6.6667
>> temp2;
no temparture was entered
>> 27