logo for matrixlab-examples.com
leftimage for matrixlab-examples.com

EXAMPLES: a custom-made Matlab function

Even though Matlab has plenty of useful functions, in this example we're going to develop a custom-made Matlab function. We'll have one input value and two output values, to transform a given number in both Celsius and Farenheit degrees.

A function file ('m-file') must begin with a function definition line. In this line we define the name of the function, the input and the output variables.

Type this example in the editor window, and assign it the name 'temperature' ('File' -> 'New' -> 'M-File'):

% This function is named 'temperature.m'.
% It has one input value 'x' and two outputs, 'c' and 'f'.
% If 'x' is a Celsius number, output variable 'f'
% contains its equivalent in Fahrenheit degrees.
% If 'x' is a Fahrenheit number, output variable 'c'
% contains its equivalent in Celsius degrees.
% Both results are given at once in the output vector [c f]
function [c f] = temperature(x)
f = 9*x/5 + 32;
c = (x - 32) * 5/9;

Then, you can run the Matlab function from the command window, like this:

>> [cent fahr] = temperature(32)

cent =

fahr =

>> [c f]=temperature(-41)

c =

f =

The receiving variables ([cent fahr] or [c f]) in the command window (or in another function or script that calls 'temperature') may have different names than those assigned within your just created function.

 From 'Matlab Function' to home

 From 'Matlab Funtion' to 'Matlab Examples'


Matrix Manipulation

Matlab Commands

footer for matlab function page