This section explains user function.
In software, it is very useful to summarize some common programs as functions.
This section shows process of creating, saving, loading and calling a function. Specific process of creating a user function is shown in figure below:
To create a function, use function...end;
block.
For example, to create a function named “realsqrt”, see code as follows:
function Y = realsqrt(X)
Y = sqrt(X);
if(any(any(imag(Y))))
error("realsqrt: realsqrt generate complex results");
end
end;
Function names follow same rules as variable names. Name must start with a letter and can contain letters, numbers, or underscores.
For more details, see Function.
The created user function realsqrt
is saved as “usr_realsqrt.msf”.
Function name and file name should be consistent to facilitate practical application. Example intuitively shows difference between function name and file name.
Note:
.msf
.Import user function using built-in function load
, see Saving and Importing Data.
To load a user function, use full path of function file. After loaded, function is displayed in Script workspace.
load("D:/usr_realsqrt.msf");
For a successfully imported user function, invoke this function by name in the script.
a = [1,4,9];
b = realsqrt(a)
After function realsqrt
is invoked successfully, result is printed in Script console:
a = [1,4,9];
b = realsqrt(a)
b =
1 2 3