MATLAB Functions


Calling a function

fctnName( parameterList )

Examples

result = cos( pi/3 )

values = [ 1  10  100  1000 ];

log10( values )



disp( log10(values) )

disp( [ 'log base 10 of ', num2str( values(3) ), ...
        ' is ', num2str( log10( values(3) ) ) ] )
 
                        

disp( ____ )

 

 

 

num2str( ____ )

 


Defining a function

Syntax:

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:

Define an inch2meter function that converts inches to meters.

function meters = inch2meter( inches )
% Converts the given inches to the equivalent in meters.
meters = 0.0254 * inches;
end

Define a bmi function to calculate BMI given a person's height (in feet and inches) and weight (in pounds).

function result = bmi( ft, in, lbs )
% Calculate the BMI for person with given height
% (in ft and in) and weight (in lbs).
% BMI = kg / m^2






In the Command Window:

>> 










Write a sin_approx function that approximates the sine function using the first four terms of the Taylor Series expansion of sine.

 

 

In sin_approx.m file:

 

 

Note: MATLAB has a built-in factorial function

Write a script that plots both sin and sin_approx over the range 0 to π.