Introduction to Matlab

By Ossama El Badawy

Adapted for SD 252 By Stuart Doherty

General

Resources

Getting help in Matlab

Matlab Basics

Commands/Skills to know

Session Snapshot

>> pwd

ans =

C:\MATLABR11\work

>> cd c:\tmp\sd372
>> pwd

ans =

c:\tmp\sd372

>> x = [1 2 3; 4 5 6]

x =

1 2 3
4 5 6

>> y = x(2,3)

y =

6

>> x = [x ; [ 8 9 0] ]

x =

1 2 3
4 5 6
8 9 0

>> clc
>> x

x =

1 2 3
4 5 6
8 9 0

>> x(:,3) = []

x =

1 2
4 5
8 9

>> whos

Name Size Bytes Class

ans 1x12 24 char array
x 3x2 48 double array
y 1x1 8 double array

Grand total is 19 elements using 80 bytes

>> ans

ans =

c:\tmp\sd372

>> clear
>> whos
>> clc
>> whos
>> z = ones(3)

z =

1 1 1
1 1 1
1 1 1

>> z = ones(3,4)

z =

1 1 1 1
1 1 1 1
1 1 1 1

>> y = zeros(5,6)

y =

0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0

>> size(y)

ans =

5 6

>> clc
>> eye(4)

ans =

1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1

>> z = 1:10

z =

1 2 3 4 5 6 7 8 9 10

>> length(z)

ans =

10

>> clc
>> z = 1:2:10

z =

1 3 5 7 9

>> clear
>> whos
>> pwd

ans =

c:\tmp\sd372

Matlab Scripts & Functions (*.m files)

Sample Function

Here is a Matlab function called "Gauss1D", implemented in file "Gauss1D.m":

function y = Gauss1d( x, mu, sigma )

y = 1/(sqrt(2*pi)*sigma)*exp(-0.5*(x-mu).^2/sigma^2) ;

Session Snapshot

>> Gauss1d( 0, 0, 1 )

ans =

0.3989

>> Gauss1d( 1, 0, 1 )

ans =

0.2420

>> Gauss1d( 0, 0, 1 )

ans =

0.3989

>> x = -10:0.1:10 ;
>> whos

Name Size Bytes Class

ans 1x1 8 double array
x 1x201 1608 double array

Grand total is 202 elements using 1616 bytes

>> y = Gauss1D( x, 0, 1 );
>> whos

Name Size Bytes Class

ans 1x1 8 double array
x 1x201 1608 double array
y 1x201 1608 double array

Grand total is 403 elements using 3224 bytes

>> plot( x, y )

>> grid on
>> axis([-10 10 0 1])

>> Figure (2)
>> for sigma=[0.5:0.5:5]; hold on; plot( x,Gauss1d(x, 0, sigma)); end

>> clear
>> whos

Sample Script

The following lines of code can be copied into a *.m file and run as a script by typing "filename.m" into the MATLAB command window. The "stem" function is useful for plotting functions of discrete variables and the "plot" function is useful for functions of continuous variables:

% Sample Script: samplescript.m

T = 10; % Sinusoid period in seconds

f = 1/T;

t = [0:2*T]; % Evaluate the sinusoid for two periods

y = sin(t*2*pi*f);

stem(t,y);

xlabel('samples');

ylabel('sin(2*pi/10*t)');

Session Snapshot

>> samplescript

Tips

Operators: