Function Example
The following code creates a new MATLAB function that
generates Gaussian noise with specified mean and
standard deviation. Type it in a file gauss.m:
1 function x = gauss(M,N,m,s)
2 %GAUSS - Generates Gaussian noise samples
3 % Usage: x = gauss(M, N)
4 % M, N: Dimensions of the output noise matrix x
5 % m, s: Mean value and standard deviation of x
6 x=m+s*randn(M,N);
Type >> help gauss to see the output message.
To run the function gauss:
1 >> y=gauss(1,1e5,0,1);
2 >> [mean(y), std(y)]
3 ans =
4 -0.0003 0.9997
Note how the variable x of the function is not available in
the workspace after the function call.
Dr. Charalampos Tsimenidis Scripts and Functions 57 /80
Scripts and Functions (Cont.)
If no output argument is used the first output variable is
stored in ans.
1 >> gauss(1,5,1,0.5)
2 ans =
3 1.4357 0.9435 0.8946 1.1852 0.8910
Functions may have multiple outputs.
1 function [x, me, se] = gauss(M,N,m,s)
2 %GAUSS - Generates Gaussian noise samples
3 % Usage: x = gauss(M, N)
4 % M,N: Dimensions of the output noise matrix x
5 % m,s: Mean value and standard deviation of x
6 % me,se: Sample mean and standard deviation of x
7 x=m+s*randn(M,N);
8 me=mean(x);
9 se=std(x);
Dr. Charalampos Tsimenidis Scripts and Functions 58 /80
Scripts and Functions (Cont.)
You may call a function without using its output arguments.
Possible calls
1 gauss(1,5,1,0.5);
2 y=gauss(1,1e5,0,1);
3 [y,mu,sigma]=gauss(1,1e5,0,1);
4 [y,mu]=gauss(1,1e5,0,1);
5 [y,˜,sigma]=gauss(1,1e5,0,1);
You can create functions that have neither input or output
arguments. Type in a file plot results.m the code
below:
1 function plot_results()
2 % Plots Gauss signal
3 plot(gauss(1,200,1,0.5),’ro’)
4 axis([ 0 200 -3 4])
5 xlabel(’Gaussian noise.’)
Run this file at the command prompt:
1 >> plot_results
Dr. Charalampos Tsimenidis Scripts and Functions 59 /80
Functions (Cont.)
Function definitions inside functions are possible.
1 function a=rayleigh(N,s)
2 [x, y]=boxmuller(N);
3 a=s*sqrt(x.ˆ2+y.ˆ2);
4
5 function [x1, x2]=boxmuller(M)
6 u=rand(2,M);
7 x1=sqrt(-2*log(u(1,:))).*cos(2*pi*u(1,:));
8 x2=sqrt(-2*log(u(2,:))).*sin(2*pi*u(2,:));
The function rayleigh is called primary.
The function boxmuller is called subfunction.
Subfunctions are only available to the primary function.
Function definitions inside functions are useful to shorten
repeated code segments.
Dr. Charalampos Tsimenidis Scripts and Functions 60 /80