Live functions are program files that contain code and formatted text together in a single interactive environment called the Live Editor. Similar to live scripts, live functions allow you to reuse sequences of commands by storing them in program files. Live functions provide more flexibility, though, primarily because you can pass them input values and receive output values.
To create a live function, go to the Home tab and select New > Live Function.
To open an existing function (.m
) as a live function
(.mlx
) from the Editor, right-click the document tab and select
Open functionName
as Live
Function from the context menu. Alternatively, go to the
Editor tab, click Save, and select Save As. Then, set
the Save as type: to
MATLAB Live Code Files
(*.mlx)
and click Save. Opening a function as a
live function creates a copy of the file and leaves the original file untouched.
MATLAB® converts publishing markup from the original function to formatted content
in the new live function.
You must use one of the described conversion methods to convert your function to a
live function. Simply renaming the function with a .mlx
extension
does not work and can corrupt the file.
After you create the live function, add code to the function and save it. For example,
add this code and save it as a function called mymean.mlx
. The
mymean
function calculates the average of the input list and
returns the results.
function a = mymean(v,n) a = sum(v)/n; end
To document the function, add formatted help text above the function definition. For example, add a title and some text to describe the functionality. For more information about adding help text to functions, see Add Help for Live Functions.
To run the live function, enter the name of the function in the Command Window. For
example, use mymean.mlx
to calculate the mean of 10 sequential
numbers from 1 to 10.
mymean(1:10, 10)
ans = 5.5000
You also can call the live function from a live script. For example, create a live
script called mystats.mlx
. Add this code that declares an array,
determines the length of the array, and passes both values to the function
mymean
.
x = 1:10;
n = length(x);
avg = mymean(x,n);
disp(['Average = ', num2str(avg)])
Run the live script. The Live Editor displays the output.
If a live function displays text or returns values, the Live Editor displays the
output in the calling live script, in line with the call to the live function. For
example, add a line to mymean
that displays the calculated mean
before returning the
value:
function a = mymean(v,n) a = sum(v)/n; disp(['a = ', num2str(a)]) end
mystats
, the Live Editor displays the output for
mymean
with the output from mystats
.