Page 830 - Mechatronics with Experiments
P. 830
816 MECHATRONICS
% equivalent to running the code in this file as if they were
typed explicity at that location.
A = [12;3 4];
B = [56;7 8];
C = A+B ;
Matrix2 ;
F = [ 50 60 ; 70 80] ;
G = E+F;
Script M-file example: Matrix2.m
% Filename: Matrix2.m
% Example of an M-script file.
% This file is executed by the "Matrix2" line in the Matrix1.m
% script file.
D = [1020;30 40];
E= C+ D;
>> Matrix1 ; % to run the Matrix1.m script file.
% Then Matrix1.m script file runs Matrix2.m
script file.
®
Calling a “user-written MATLAB function” follows the function call rules similar
to the rules used in high level programming languages such as C and Fortran: it accepts input
arguments in the function call and returns data. The data defined locally in the function are
local to the function file. Unlike the script M-files, they are not globally accessible. Likewise,
the function can access only the data variables passed through the function call argument
list. It cannot access the variables in the workspace. The only way to override that is to
define “global” variables. Good programming practice suggests that we use M-function
files with controlled local data scope, and minimize the use of M-script files with global
data scope or “global” statement that can lead to unintended data over-writes. The syntax of
®
a user-written MATLAB function M-file is as follows (filename is the function-name with
extension “.m”),
Filename: function_name.m
function [Y,Z] = function_name(input_1, input_2)
% 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
Y= 5.0 ∗ input_1 ;
Z= 10.0 ∗ input_2 ;
% Return (output) variables Y and Z must appear on the left
hand side of
% assignment operator.
%
% This is the end of the function.