Page 831 - Mechatronics with Experiments
P. 831
®
®
MATLAB , SIMULINK , STATEFLOW, AND AUTO-CODE GENERATION 817
®
MATLAB Example for M-Function File
% Filename: Example1.m
%
%
x=[0.0:0.1:2∗pi];
y = My_Function1(x) ;
plot(x,y) ; % This will plot the sine function on Figure 1.
grid on;
% End of file
function z1 = My_Function1(u1)
% Input variable to this function from the caller: input_1,
input_2, ...
% Output variable from this function to the caller: Y, Z
%
% Local data
%
% Logic
%
% I/O
z1 = My_Function2(u1) ; % Let’s illustrate that function
calls can be nested.
% Return (output) z1 must appear on the left hand side of
% assignment operator.
%
% This is the end of the function.
function y1 = My_Function2(x1)
% Input variable to this function from the caller: input_1,
input_2, ...
% Output variable from this function to the caller: Y, Z
%
% Local data
%
% Logic
%
% I/O
y1 = sin(x1) ;
% Return (output) y1 must appear on the left hand side of
% assignment operator.
%
% This is the end of the function.
The result is shown in Figure A.3.
®
Global variables can be defined in MATLAB for data variables to be shared across
functions without having to pass it in the input–output arguments. However, a global
data definition violates the “encapsulation” principle in programming. Therefore, it is not
recommended for good programming practice. However, if it must be used, the global
variables are declared both in M-script file (i.e., the M-script file which holds your