Академический Документы
Профессиональный Документы
Культура Документы
Outline
! MATLAB Programming
! MATLAB Procedures ! MATLAB Functions ! MATLAB Language Constructs ! The Function eval ! Function Handles
MATLAB Procedures
! Script files: MATLAB command sequences
! m-files (proced.m) ! must be in the path ! executed as a new command (proced) ! can check for the existence of a command using exist ! can get information about a command using help. The heading is the documentation.
! The variables defined in the script file are known in the MATLAB workspace.
An example: fnExample.m
% % % % % % % % % % % % % Procedure fnExample call: fnExample first example of a script file book: MATLAB und Simulink Author: Prof. Dr. Ottmar Beucher Karlsruhe Polytechnic -- Engineering and Economics Version: 1.03 Dates: 01/31/1998,3/21/2002,9/14/2005
t=(0:0.01:2); sinfct=sin(2*pi*5*t); cosfct=2*cos(2*pi*3*t); expfct=exp(-2*t); plot(t,[sinfct; cosfct; expfct]) xlabel ('time / s') ylabel('Amplitude') title('three gorgeous signals')
MATLAB Functions
! Ability to pass parameters (back and forth)
! Input parameters ! Output parameters
! Function names and file names must be in agreement ! Input parameters are local ! Within a function, no access to workspace ! No call-by-reference
An example: fnExample2.m
function [t, sinfct, cosfct, expfct]= fnExample2(f1, f2, damp) % % Function fnExample2 % % call: [t, sinfct, cosfct, expfct] = fnExample2(f1, f2, damp) % or fnExample2(f1, f2, damp) % % First example of a MATLAB function % % Normally both a description of the input and output % parameters and the important characteristics of the % function are given here % % Book: Introduction to MATLAB & SIMULINK % A Project Approach % % Author: Prof. Dr. Ottmar Beucher t=(0:0.01:2); sinfct=sin(2*pi*f1*t); cosfct=2*cos(2*pi*f2*t); expfct=exp(-damp*t); plot(t,[sinfct;cosfct; expfct]) xlabel ('time / s') ylabel('Amplitude') title('three gorgeous signals')
Another Example
function [sum] = fnExample3(a,b) % % function fnExample3 % % call: [sum] = fnExample3(a,b) % % second example of a MATLAB function % % Calculates the sum of two vectors a and b, % which must, of course, also have the same dimensions, % but which will not be checked in this version of the program. % % This should clarify the properties of local variables. % % Book: Introduction to MATLAB & SIMULINK % A Project Approach % % Author: Prof. Dr. Ottmar Beucher sum = a+b; % It should do this. a = a.^2; % And now a little experiment. % squaring the components of a
Control Flow
if else elseif end for while break continue switch case otherwise return error - Conditionally execute statements. - Execute statement if previous IF condition failed. - Execute if previous IF failed and condition is true. - Terminate scope of control statements. - Repeat statements a specific number of times. - Repeat statements an indefinite number of times. - Terminate execution of WHILE or FOR loop. - Pass control to the next iteration of a loop. - Switch among several cases based on expression. - SWITCH statement case. - Default SWITCH statement case. - Return to invoking function. - Display message and abort function.
Book: Introduction to MATLAB & SIMULINK A Project Approach Author: Prof. Dr. Ottmar Beucher
magn = abs(cmplxNum);
% Calculate the real and imaginary parts
continued
% Determine the quadrant if cmplxNumRe > 0 if cmplxNumIm >= 0 % first quadrant radians = atan(cmplxNumIm/cmplxNumRe); else % fourth quadrant radians = atan(cmplxNumIm/cmplxNumRe) + 2*pi; end; elseif cmplxNumRe < 0 % second and third quadrants radians = atan(cmplxNumIm/cmplxNumRe) + pi; else % special case: real part = 0 if cmplxNumIm >= 0 % imaginary part positive radians = pi/2; else % imaginary part negative radians = 3*pi/2; end; end; % recalculating the argument in deg degrees = radians*180/pi;
continued
% calculate the magnitude of the vector N = length(nums); % the variable avgval, the average, is % initialized to 0 avgval = 0; % adding the components to avgval, one after the other for k=1:N % do this from the 1st to the Nth component avgval = avgval + nums(k); end % Divide avgval by the number of numbers (N) avgval= avgval/N;
Nums mval
Book: Introduction to MATLAB & SIMULINK A Project Approach Author: Prof. Dr. Ottmar Beucher
continued
% calculate the magnitude of the vector N = length(nums); % the variable mval, the maximum value, is % initialized to the first value of the variable mval = nums(1); % search the components, one after the other for k=2:N % do this from the 2nd to the Nth component if nums(k) > mval % Compare the current component mval = nums(k);% with the previous maximum: if it is end % greater, assign this number to mval end
An example of handling the while-construct in MATLAB This example prompts the user to input data and saves these data in a vector [InVector]. This procedure is repeated until a NEGATIVE number is read in. input parameter: output parameter: none InVector values read in
Book: Introduction to MATLAB & SIMULINK A Project Approach Author: Prof. Dr. Ottmar Beucher
continued
% Prompting the user to input data % dat contains the input datum dat = input('Input a number! (End if negative):'); InVector = dat; % Initialize InVector with this % Checking and reading in further data, until % the end criterion is satisfied while dat >= 0 % as long as the datum is positive: % read in the next number dat = input('Input a number! (End if negative):'); % append to InVector InVector= [InVector; dat];
end;
vector operation
real vector String indicating the operation to be performed: 'l2norm', 'max','min','l1norm', 'average', 'maxnorm', 'length' calculated value
result
% % Book: Introduction to MATLAB & SIMULINK % A Project Approach % % Author: Prof. Dr. Ottmar Beucher
continued
% Calculating the desired quantity corresponding to operation
result = min(vector);
case 'l1norm'
% sum of the contributions of the components result = sum(abs(vector)); % largest magnitude of the components result = max(abs(vector)); % average value of the components
end;
switch-construct
An example with nargin and nargout
function [t, sinfct, cosfct] = FSwitchIn(f1, f2, damp) % function FSwitchIn % % call: [t, sinfct, cosfct] = FSwitchIn(f1, f2) % or [t, sinfct, cosfct] = FSwitchIn(f1, f2, damp) % % An example of an MATLAB function with a variable % number of input parameters % % Book: Introduction to MATLAB & SIMULINK % A Project Approach % % Author: Prof. Dr. Ottmar Beucher t=(0:0.01:2);
continued
switch nargin case 2 sinfct = sin(2*pi*f1*t); cosfct = 2*cos(2*pi*f2*t); plot(t,[sinfct; cosfct]) xlabel('time / s') ylabel('Amplitude') title('sine and cosine oscillations') case 3 sinfct = sin(2*pi*f1*t); cosfct = 2*cos(2*pi*f2*t); expfct = exp(-damp*t); plot(t,[sinfct; cosfct; expfct]) xlabel('time / s') ylabel('Amplitude') title('three gorgeous signals') otherwise msg = 'The function FSwitchIn must have 2'; msg = strcat(msg, ' or 3 input parameters!'); error(msg); end
continued
if nargout < 3 msg = 'The function FSwitchIn should return a time'; msg = strcat(msg, 'vector and two sine signals!'); error(msg); end
! The string theCommands is interpreted as a MATLAB command sequence via the eval command ! Makes more sense in a program than in interactive mode
A Brief Example
function [] = FprintfEval(x, digits, post) % % Function FprintfEval % % call: FprintfEval(x, digits, post) % % sample call: FprintfEval(x, 10, 7) % % Example of a MATLAB function which is used within % the function eval for constructing commands. % A vector is to be displayed on the screen as a % column along with a prescribed format. % % input parameters: x a vector % digits width of the number % post number of places % after decimal point % % output parameters: none
continued
N = length(x); % set the number of values digs = num2str(digits); % convert number of places into a string psts = num2str(post); % convert number of places after decimal % point into a string for k=1:N printcommand = ... ['fprintf(''%', digs,'.', psts, 'f\n'',', num2str(x(k)),')']; eval(printcommand); end
Function Handles
! In MATLAB, functions can be passed on to other MATLAB functions across lists of parameters as so-called function handles. ! A function handle corresponds to a pointer to the function and results when an @ is placed in front of the function involved.
!!clear !!FH_sin = @sin !!value = FH_sin(2)
Prior to MATLAB 7:
!!value = feval(FH_sin ,2)
An Example
function [integral] = fnExample4(a, b, F, N) % % Function fnExample4 % % call: [int] = fnExample4(a, b, F, N) % % sample call: integ = fnExample4(2, 4, @tstfnct, 3) % % An example of manipulating function handles % % The present example calculates the integral of % the function F, whose name is passed on as % a function handle to fnExample4, over the limits [a,b]. % Simpson's rule is used to calculate the integral; % for that the range of integration is partitioned % into two times N intervals. % % Book: Introduction to MATLAB & SIMULINK % A Project Approach % % Author: Prof. Dr. Ottmar Beucher
continued
% partitioning the interval [a,b] (setting the points) h=(b-a)/(2*N); intval=(a:h:a+2*N*h); integral = F(a)+F(b); % subinterval length % points marking subintervals % F at the limits of the interval % F at the subinterval points with % odd indices for i=3:2:2*N integral = integral+2*F(intval(i)); end; % F at the subinterval points with % even indices for i=2:2:2*N integral = integral+4*F(intval(i)); end; integral = integral*h/3; % normalizing with h/3
Example Usage
!! simpint = fnExample4(2, 4, @tstfnct, 3) function [y] = tstfnct(x)
% % Call: [y] = tstfnct(x) % % Example function to test fnExample4 % % There are NO incorrect inputs !! % % Book: MATLAB and Simulink A Project Approach % % Author: Prof. Dr. Ottmar Beucher % HS Karlsruhe - Technik and Wirtschaft % Version: 1.01 % Dates: February 02, 1998/March 26, 2002/September 14, 2005
y=2*cos(x)*exp(-x)+1;