2016/11/04

Matlab: Custom Function 自定函數

To create a custom function, the function name has to be identical to the *.m file name. (函數名稱必須與m檔案的名稱一致。)

Create a new script and edit it as:

function outputName = MyFunctionName(a,b)
% This function muliplies a by b and returns the result as outputName

outputName = a*b;

Save the script as MyFunctionName.m.

If a custom function is not properly defined or the path is incorrect, Matlab may return an error like this:

Undefined function or variable 'MyFunctionName'.

Hot to set the path for M files:

Home -> Environment -> Set Path

Example of Matlab 2015 b (Mac):


Call the M file from the Matlab terminal:

>> MyFunctionName(2,3)

ans =

     6

==============
Example to return multiple vectors with unequal dimensions:

function [a, b] = MyFunc(in1, in2)
a = [in1;1;2];
b = [in2 in2*2 in2*3 in2*4];

Save the code above as MyFunc.m.

Execute the function as below:

>> [a, b] = MyFunc(1,2)

a =

     1
     1
     2


b =

     2     4     6     8

Related Information 參考資料

Common Errors When Calling Functions (MathWorks)

沒有留言:

張貼留言