DREAM IDEA PLAN IMPLEMENTATION Introduction to Matlab Present
DREAM IDEA PLAN IMPLEMENTATION
Introduction to Matlab Present to: Amirkabir University of Technology (Tehran Polytechnic) & Semnan University Dr. Kourosh Kiani Email: kkiani 2004@yahoo. com Email: Kourosh. kiani@aut. ac. ir Web: aut. ac. com 2
Course Structure • Spread over 8 weeks • 1 classes per week • 2 hour per class
Programming in Matlab
Functions • A function is a black box that gets some input and produces some output • We do not care about the inner workings of a function • Functions provide reusable code • Functions simplify debugging • Functions have private workspaces – The only variables in the calling program that can be seen by the function are those in the input list – The only variables in the function that can be seen by the calling program are those in the output list
Functions output argument factorial. m: name of the function input argument function p = factorial(n) %FACTORIAL Factorial function. % FACTORIAL(N) is the product of all the integers from 1 to N, % i. e. prod(1: N). Since double precision numbers only have about % 15 digits, the answer is only accurate for N <= 21. For larger N, % the answer will have the right magnitude, and is accurate for % the first 15 digits. % H 1 comment line % See also PROD. if (length(n)~=1) | (fix(n) ~= n) | (n < 0) error('N must be a positive integer'); end p = prod(1: n); other comment lines executable code
Functions • The function statement marks the beginning of a function • The name of the function must be the same as the name of the m-file • The lookfor command searches functions according to the H 1 comment line • The help command displays the comment lines from the H 1 line until the first non-comment line
Function Examples four variables declared as input arguments function distance = dist 2(x 1, y 1, x 2, y 2) %DIST 2 Calculate the distance between two points % Function DIST 2 calculates the distance between % two points (x 1, y 1) and (x 2, y 2) in a Cartesian % coordinate system. % Define variables: % x 1 -- x-position of point 1 % y 1 -- y-position of point 1 % x 2 -- x-position of point 2 % y 2 -- y-position of point 2 % distance -- Distance between points % Calculate distance = sqrt((x 2 -x 1). ^2 + (y 2 -y 1). ^2);
Function Examples • help dist 2 DIST 2 Calculate the distance between two points Function DIST 2 calculates the distance between two points (x 1, y 1) and (x 2, y 2) in a Cartesian coordinate system. • lookfor distance DIST 2 Calculate the distance between two points GFWEIGHT Calculate the minimum distance of a linear. . . DISTFCM Distance measure in fuzzy c-mean clustering. .
Function Examples function [mag, angle] = polar_value(x, y) %POLAR_VALUE Converts (x, y) to (r, theta) % Function POLAR_VALUE converts an input (x, y) % value into (r, theta), with theta in degrees. % It illustrates the use of optional arguments. % Check for a legal number of input arguments. msg = nargchk(1, 2, nargin); error(msg); % If the y argument is missing, set it to 0. if nargin < 2 y = 0; end error check for input % Check for (0, 0) input arguments, and print out optional % a warning message. if x == 0 & y == 0 msg = 'Both x any y are zero: angle is meaningless!' ; warning(msg); end input argument % Now calculate the magnitude. mag = sqrt(x. ^2 + y. ^2); % If the second output argument is present, calculate % angle in degrees. if nargout == 2 angle = atan 2(y, x) * 180/pi; end optional output argument
Functions: Optional Arguments • Optional arguments can be checked using: – nargchk: validates number of arguments – nargin: number of input arguments – nargout: number of output arguments Use nargchk inside an M-file function to check that the desired number of input arguments is specified in the call to that function. msgstring = nargchk(minargs, maxargs, numargs) returns an error message string msgstring if the number of inputs specified in the call numargs is less than minargs or greater than maxargs. If numargs is between minargs and maxargs (inclusive), nargchk returns an empty matrix.
Function Examples • [ m, a ] = polar_value ? ? ? Error using ==> polar_value Not enough input arguments. • [ m, a ] = polar_value( 1, -1, 1 ) ? ? ? Error using ==> polar_value Too many input arguments. • [ m, a ] = polar_value( 1, -1 ) m= 1. 4142 a= -45 • m = polar_value( 1, -1 ) m= 1. 4142
function s = add(x, y, z) if nargin < 2 error(’At least two input arguments are required. ’) end if nargin == 2 s = x + y; else s = x + y + z; end
Function Examples
Function Examples
Function Examples
Function Examples
Function Examples
Function Examples
Script Files • You can save a sequence of commands for reuse later • Create a new M-File (script file)
Script Files • Each line is the same as typing a command in the command window • Save the file as vol_surf. m
Script Files • Run the sequence of commands by typing the filename in the command window >> vol_surf r= 5 h= 10 volume = 785. 3982 area = 471. 2389 >>
Script Examples % Script file: test_dist 2. m % % Purpose: % This program tests function dist 2. % % Define variables: % ax -- x-position of point a % ay -- y-position of point a % bx -- x-position of point b % by -- y-position of point b % result -- Distance between the points % Get input data. disp('Calculate the ax = input('Enter x ay = input('Enter y bx = input('Enter x by = input('Enter y distance value of between two points: '); point a: '); point b: '); % Evaluate function result = dist 2 (ax, ay, bx, by); % Write out result. fprintf('The distance between points a and b is %fn', result);
Script Examples >>test_dist 2 Calculate the distance between two points: Enter x value of point a: 1 Enter y value of point a: 1 Enter x value of point b: 4 Enter y value of point b: 5 The distance between points a and b is 5. 000000
Functions & scripts • Both scripts and functions are saved as m-files • Functions are special m-files that receive data through input arguments and return results through output arguments • Scripts are just a collection of MATLAB statements • Functions are defined by the function statement in the first line • Scripts use the global workspace but functions have their own local independent workspaces
Conditional Statements • Dissecting the conditional: • “If it is sunny outside then I will have a picnic. ” dependent condition • “If the All Blacks win then I will be happy. ” condition dependent – Using MATLAB • “If a < b then disp(a)” condition dependent
if … end • Syntax if condition some commands end dependent end lets MATLAB know when the conditional statement is finished
if … end Example
if … else … end • Syntax if condition some commands else some other commands end This section is OPTIONAL end lets MATLAB know when the conditional statement is finished
if … else … end Example
if … else … end Example function y = absval(x) if x >= 0 y = x; else y = -x; end function y = absval(x) y = x; if y < 0 y = -y; end
function y = signum(x) if x > 0 y = 1; elseif x == 0 y = 0; else y = -1; end
function y = f(x) if x == 0 y = 1; else y = sin(x)/x; end
function y = count(x) switch x case 1 y = ’one’; case 2 y = ’two’; otherwise y = ’many’; end
if … elseif … end
Pseudocode and Flowcharts • Pseudocode – Text description of program steps. • May contain fragments of code. • Doesn’t contain the nitty-gritty details. – Can use this to program any language. • Flowcharts – Geometric symbols to describe program steps. – Captures the “flow” of the program. – Also useful for any programming language.
Flowchart Elements Basic step Interaction with user Check condition Program flow
Loops • Sometimes in your programs you will want to “loop”. – repeat some commands multiple times • You may know how many times you want to loop. – for loop • You may be looping until something happens (conditional loop). – while loop
Example • Maybe you want to write out the squares of the integers from 2 to 7 Pseudocode for i = 2 to 7 by 1 display i 2 end
Flowcharts for Loops Flowchart – for loops Change i by step Some commands NO i = start is i > finish YES
Example for loop i=i+1 Display i 2 NO i=2 is i > 7 YES
MATLAB for loops for variable = start: step: finish some commands end – If no step specified assumed to be 1
Different step values
MATLAB for loops
MATLAB for loops
MATLAB for loops
MATLAB for loops The typical ‘for’ loop looks like: for i = 1: 2: 13 … end Which is the same as: for i = [1 3 5 7 9 11 13] … end
MATLAB for loops
MATLAB for loops Note: The MATLAB way to write that program would have been: b = sum([ 3 9 17]); Avoid loops if possible !
MATLAB for loops
MATLAB for loops
MATLAB for loops Use loop to determine the minimum m
MATLAB for loops
MATLAB for loops
While loops • Maybe you want to write out squares of integers (starting at 1) until the square exceeds 50. while some condition is true some commands end
Example Pseudocode i=1 while i 2 <= 50 display i 2 i=i+1 end
Flowchart for a while loop is some condition true Initialise loop NO YES Update loop i=2 Some commands i 2 50 YES i=i+1 Display i 2 NO
while loop Example
while loop Example
while loop Example
while loop Example
Infinite Loops • “Infinite loop” = piece of code that will execute again and again … without ever ending. • Possible reasons for infinite loops: – getting the conditional statement wrong – forgetting the update step • If you are in an infinite loop then ctrl-c stops MATLAB executing your program.
Infinite Loops
Infinite Loops
1/1^4 + 1/2^4 + 1/3^4 +· · ·, n = 1; oldsum = -1; newsum = 0; while newsum > oldsum = newsum; newsum = newsum + nˆ(-4); n = n + 1; end newsum
1/1^4 + 1/2^4 + 1/3^4 +· · ·, newsum = 0; for n = 1: 100000 oldsum = newsum; newsum = newsum + nˆ(-4); if newsum == oldsum break end newsum
Booleans and while loops • Use a boolean to control while loop still. Looping = true; while still. Looping some commands if some conditions still. Looping = false; end
Booleans Example
Switch, Case, and Otherwise
Matlab Program …
Matlab Program …
Matlab Program … Click this icon
Matlab Program …
Matlab Program …
Questions? Discussion? Suggestions ?
- Slides: 76