MATLAB provides a powerful library of functions for user invocation, but also supports user-defined functions. This article uses an example from Vanderbilt University Professor Akos Ledeczi to explain how to customize functions in MATLAB in a step-by-step way.
First, enter the edit command in the command window to begin editing the function. The function is to randomly generate a matrix of 3 rows and 4 columns, and the elements of the matrix are in the range of 0-1.
function Myranda = rand (3,4) end
where function and end are keywords, function means that the file is a function, and end represents the end of the body of the function. Executing the myrand command in the command window results in the following:
>> Myranda = 0.5688 0.3371 0.3112 0.6020 0.4694 0.1622 0.5285 0.2630 0.0119 0.7943 0.1656 0.6541
Then, add parameters to the function. The function is to randomly generate a matrix of 3 rows and 4 columns, and the elements of the matrix are in the range of Low-high.
function A = Myrand (low, high) A = Low+rand (3,4) * (high-low); end
where low and high are the two input parameters of the function body, which represent the upper and lower bounds of the value range of the matrix element respectively; A is the range value of the function. Executing the myrand command in the command window results in the following:
>> Myrand (1,6) ans = 4.4461 1.4191 1.7619 5.9807 4.7408 2.1449 5.1291 1.3909 3.2527 5.5667 3.6917 3.2134
Finally, add a return parameter to the function. The function adds each element of a randomly generated matrix and returns its sum.
function [A, S] = Myrand (low, high) A = low + rand (3,4) * (high-low), V = a (:); s = sum (v); end
where S is the newly added return parameter. Executing the myrand command in the command window results in the following:
>> [x SS] = Myrand (2,4) x = 3.1504 2.7063 2.0860 3.4634 2.1196 3.6424 2.3380 3.2955 2.4696 2.0308 3.2982 2.9018ss = 33.5021
So far, the simple way to customize functions in MATLAB has been introduced. MATLAB also supports common looping and judging structures such as for-loop and If-else, see subsequent blogs.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
MATLAB Custom Functions