MATLAB Functions


Defining a function

function returnValue = functionName ( parameterList )
% Comments describing what the function does, the
% inputs to the function, and the return value.
 
code that does the work of the function
 
returnValue = some calculated value
 
end 

Examples:

In inch2meter.m:

function meters = inch2meter( inches )
% Converts the given number of inches to meters
meters = 0.0254 * inches;

In bmi.m:

function result = bmi( feet, inches, pounds )
% Determines the BMI for a person whose height is expressed as the
% given feet and inches (e.g., 5 feet 7 inches) and weight is the
% given number of pounds. Note: BMI = weight(kg) / height(m)^2
meters = inch2meter( feet*12 + inches );
kilos = 0.4536 * pounds;
result = kilos ./ meters.^2;

Returning multiple results

Option 1

function result = meter2feet_v1(meters)
% Converts the given number of meters to feet & inches
in = 39.3701 * meters;
ft = floor(in/12);
in = in - ft*12;
result = [ft ; in];

Option 2

function [ft, in] = meter2feet_v2(meters)
% Converts the given number of meters to feet & inches
in = 39.3701 * meters;
ft = floor(in/12);
in = in - ft*12;