logo for matrixlab-examples.com
[?] Subscribe To This Site

XML RSS
Add to Google
Add to My Yahoo!
Add to My MSN
Subscribe with Bloglines


Home
Matrixmania Blog
Contact
-> Sitemap <-
Matlab Books
Quick Matlab Guide
Matlab Tutorials
Matlab Examples
Matlab Flow Control
Boolean Algebra
Linear Algebra
Matlab 2D Plots
Matlab 3D Plots
Matlab GUI
Matlab Cookbook I
Matlab Cookbook II
Probability and Stats
Forums and Help
Relevant Links
Fun!
Your own Website?
Terms/Policies
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 =
     0

fahr =
   89.6000

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

c =
  -40.5556

f =
  -41.8000

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'


footer for matlab function page