Sie sind auf Seite 1von 8

MATLAB, A PRIMER

MATLAB (MATrix LABoratory) is a Matrix Vector Oriented Programming language with significant
graphics capabilities

Three display Windows

Command Window: enter commands and data and print results

>> MATLAB prompt indicator in command window

Graphics Window: Display plots and graphs

Edit Window: Create and modify M-files.


Programs in MATALB are called SCRIPT or COMMANDS
Programs are stored in Subdirectories as .m files
Subdirectories are linked to command window

Useful commands (can enter by script or from command window)

clf clear figure

close all closes all figures

clear all clears all arrays generated in executed script

control c aborts running script file (often indicated as ^c, but ^ is short for control key, not carrot)

who inquiry to list active variables

whos inquiry to list variables and their sizes

size(x) lists dimensions of variable x

length(x) list length of variable x

format long (default, 4-decimals) 3.1416


format short (14 decimals) 3.14159265358979

help qwerty query seeking information about argument qwerty


example
>> help length
LENGTH Length of vector.
LENGTH(X) returns the length of vector X. It is equivalent
to MAX(SIZE(X)) for non-empty arrays and 0 for empty ones.
Operators + a+b (plus sign), addition operator
- a–b (minus sign), subtraction operator
* a*b (asterisk , multiply sign), multiplication operator
/ a/b (forward slant), division operator
^ a^b (carrot), exponentiation operator

Array Operators Modify with . (dot) operator


+ a+b (plus sign), addition operator
- a–b (minus sign), subtraction operator
* a.*b (asterisk , multiply sign), multiplication operator
/ a./b (forward slant), division operator
^ a.^b (carrot), exponentiation operator

Other Notations % (percent sign) comment, anything to right is not read by matlab
% (percent sign) at top of m files is written to screen in response to help qwerty
; (semicolon) end row and suppress printing
: (colon) vector generation
… (ellipsis) continue line
‘ (single quote) transpose
( ) (left and right parenthesis) subscript enclosure
[ ] (left and right square bracket] matrix enclosure
, (comma) separator

Special symbols or command


pi represents π
i, j imaginary indicator
Inf represents ∞
NaN Not a number (eg 0/0)

zeros(3) 3-element row vector of zeros


zeros(1,3) 3-element row vector of zeros
zeros(3,4) 3 x 4 matrix of zeros

ones(3) 3-element row vector of ones (“1”)


ones(1,3) 3-element row vector of ones (“1”)
ones(3,4) 3 x 4 matrix of ones (“1”)

eye(3) 3 x 3 identity matrix


eye(3,2) 3 x 2 matrix (3 rows, 2 columns)
with ones on diagonal
1 0
0 1
0 0
Variables: Variables are entered and presented as scalars, vectors, and matrices
All variables can contain real or complex values
Complex variables are denoted as x + j*y, or as x + i*y,
j and i are reserved variable names used as indicator

examples:
a=3.4 a=[3.4] scalar
b=3.4+j*2.6 b=[3.4+j*2.6] scalar

c=[1.5 2.7] 1 x 2 vector


(no commas separating entries)
d=[1.5 2.7]’ 2 x 1 vector
d=[1.5;2.7] 2 x 1 vector
d=[1.5 2 x 1 vector
2.7]

d=[2.5 4.4; 1.7 0.1; 9.3 1.2] 2 x 3 matrix

dd=1:10 1 x 10 vector
ee=[1:5]’ 5 x 1 vector

Plotting: figure opens new figure


figure(3) opens figure and labels it number 3

subplot(m,n,p) creates axis in tiled position, m-rows, n-columns, p-th position


subplot(m n p) same

subplot(2,1,1) forms 2 subplots, 2 rows, 1 column, selects subplot 1

plot(x,y) plot y array on y axis against argument in x array on x-axis


plot(y) plot y array on y axis against count index 1 2 3….length(y)

plot(x,y,’r’) plot y vrs x as red line (see help plot)

plot(x,y1,’r’) plot y1 vrs x as red line


hold on sets toggle keeping previous plot
plot(x,y2,’:r’) plot y2 vrs x as dotted red line (see help plot)
hold off resets toggle keeping previous plots

plot(x,y1,’r’,x,y2,’:r’) multiple curves on same graph as above

axis([xmix xmax ymin ymax]) scales the current plot.


axis(‘square’) sets axis box to a square box

text(x,y,'string') text annotation: Places text in string at location x,y on figure


text(x,y,[‘name’,num2str(var,’%7.2f%’)])
assigns value of “var” to text string
b blue . point - solid
g green o circle : dotted
r red x x-mark -. dashdot
c cyan + plus -- dashed
m magenta * star (none) no line
y yellow s square
k black d diamond
v triangle (down)
^ triangle (up)
< triangle (left)
> triangle (right)
p pentagram
h hexagram

PLOT(X,Y,'c+:') plots a cyan dotted line with a plus at each data point;
PLOT(X,Y,'bd') plots blue diamond at each data point but does not draw a line.

subplot(2,1,1)
plot(0:100,cos(2*pi*(1:100)/50))
hold on
plot(0:100,sin(2*pi*(1:100)/50),’- -‘,linewidth’,2)
hold off
grid on
axis([0 100 -1.2 1.2])
title(‘cosine(2*\pi*(1:100)/50)’)
xlabel(‘counting index’)
ylabel(‘amplitude’

subplot(2,1,2)

plot(0:100,sin(2*pi*(1:100)/50))
hold on
plot(0:5:100,sin(2*pi*(1:5:100)/50),’o’)
hold off
grid on
axis([0 100 -1.2 1.2])
Common Math Functions

abs(x) absolute value of each element in array x


sqrt(x) square root of each element in array x
round(x) rounds each element of array x to nearest integer
fix(x) rounds each element of array x to nearest integer towards 0
floor(x) rounds each element of array x to next lower integer
ceil(x) rounds each element of array x to next higher integer
sign(x) +1 if x>0, -1 if x<0, 0 if x=0
rem(x,y) remainder r of x=q*y+r (modulus operator)
exp(x) e^x
log(x) log_e(x) or ln(x)
log10(x) log_10(x)

sin(x) sin(x) x in radians


cos(x) cos(x) x in radians
tan(x) tan(x) x in radians
asin(x) inverse or arc sin(x)
acos(x) inverse or arc cos(x)
atan(x) inverse or arc tan(x)
atan2(y,x) inverse or arc tan(y/x) with angle in proper quadrant

complex operators
conj(aa) conjugates argument aa
real(aa) real part argument aa
imag(aa) imaginary part argument aa
abs(aa) absolute value of argument aa
angle(aa) atan2(imag(aa),real(aa))

polynomial operations
polyval(aa,x) evaluates polynomial with coefficients aa at argument values x
conv(aa,bb) convolves two polynomial sequence (product of two polynomials)
roots(aa) factors polynomial aa and lists roots

random and statistics


rand(1,n) uniform in 0-1 random numbers, row vector of length n
rand(2,4) 2 x 4 array containing uniform random entries
rand(5) 5 x 5 array containing uniform random entries

randn(1,n) Gaussian, zero mean, unit variance, row vector of length n

var(aa) Variance of sequence in array aa


mean(aa) Mean of sequence in array aa
std(aa) standard deviation of sequence in array aa

interesting operators
fliplr(aa) reverses order of row elements
flipud(aa) reverses order of column elements
fftshift(aa) swaps first half of array with second half

reshape(aa,m,n) maps element of array aa into an m x n array


hist(aa,m) histogram bins the elements of aa into m equally spaced cells

signal processing

fft(xx)
freqz(bb,aa)
zplane(bb,aa)

hh=remez(nn,[f1 f2 f3 f4],[g1 g2 g3 g4],[w1 w2])

[bb,aa]= butter(nn,f1)
[bb,aa]= tcheby1(nn,r1,f1)
[bb,aa]= tcheby2(nn,r2,f1)
[bb,aa]= ellip(nn,r1,r2,f1)

filter(aa,bb,x)
sinc(t1:dt:t2)

hanning(nn)
kaiser(nn,beta)

programming

bad MATLAB code


for n=1:1000
y(n) = cos(2*pi*0.1*n);
end
better MATLAB code
y=cos(2*pi*0.1*(0:999));
or
y=cos(2*pi*(0:0.1:99.9))
pause pauses script file, waits for user response (enter)
pause(tt) pause tt seconds, tt > .01

Sample MATLAB Script File

% move and plot sine wave across array


figure(2)
reg=zeros(1,1000);
reg(1:100)=sin(2*pi*(0:99)/100);
for nn=1:1001
plot(0:999,reg);
grid on
axis([0 1000 -1.1 1.1])
pause(0.01)
reg=[reg(1000) reg(1:999)];
end

input prompt for user input.


frq = input('enter input frequency (cycles/interval): freq_in = ‘)

Sample MATLAB Script File

% move and plot sine wave across array


figure(3)
reg=zeros(1,1000);
frq = input('enter input frequency (cycles/interval): freq_in = ')
reg(1:100)=sin(2*pi*(0:99)*frq/100);
for nn=1:1001
plot(0:999,reg);
grid on
axis([0 1000 -1.1 1.1])
pause(0.01)
reg=[reg(1000) reg(1:999)];
end
Sample MATLAB Script File

hh=remez(42,[0 15 20 40]/40,[1 1 0 0],[1 10]);

figure(1)
subplot(2,1,1)
stem(0:42,hh,'linewidth',2)
grid on
axis([-5 45 -0.1 0.5])
title('Impulse Response')
xlabel('Normalized Time: (t/T)')
ylabel('Amplitude')

subplot(2,1,2)
plot((-0.5:1/1024:0.5-1/1024),fftshift(20*log10(abs(fft(hh,1024)))),'linewidth',2);
grid on
axis([-0.5 0.5 -70 5])
title('Frequency Response')
xlabel('Normalized Frequency: (f/f_S)')
ylabel('Amplitude')

axes('position',[0.362 0.2 .31 .1])


plot((-0.5:1/1024:0.5-1/1024),fftshift(20*log10(abs(fft(hh,1024)))),'linewidth',2);
grid on
axis([-0.2 0.2 -0.2 0.2])
title('Zoom to Passband')

Das könnte Ihnen auch gefallen