M Files and Functions

If you want to use your own function (e.g. stats), you should create an m-file (named stats.m for the function stats) and save this file in a directory on the Matlab path. On the Mac or PC, you can create m-files conveniently from under New on the File menu.

For example, the contents of stats.m might be:

% "stats.m" (function file)
%  Usage: [ xbar, std_dev ] = stats(x,n)
%  to average the first n elements of vector x.
function [xavg,s] = stats(x,n)

	for i=1:n
	    tot = tot+x(i);
	    totsq = totsq +x(i)^2;
	xavg = tot/n;
	if n > 1
	   s = sqrt(totsq - tot^2/n)/(n-1))
Last Update: September 25, 2000

[Mathlab Home | Math]