Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

Introduction to MATLAB

Interpreted Language Efficient in manipulating vectors and matrices. Slow in handling loops. Case sensitive

Creation of variables: >> v = zeros(1, 5) >> m = ones(2, 2) >> v = [1 2 4 8 16] >> w = [ 0: 0.5 : 3 ] >> m = [0.1 0.3 ; 0.2 3] Call for values: >> v ( or v(:) ) >> v(5) >> w(2:4) >> m(1,2) >> m(:,1) Dimensionality must agree! for the operations of + , -, *, /, \ Careful about matrix arithmetic operations and matrix element wise operations. That means * Vs .* and / Vs ./ Built-in constants: pi eps--smallest value Matlab can handle inf--largest value Matlab can handle Built-in functions: sqrt sin cos exp log2 log10 log max min avg abs norm erfc BesselJ filter freqz fft ifft spectrum rand randn find sort sum prod conv Note: See matlab_quickref.pdf for a list of useful Matlab built-in functions Control flow The syntax of the for loop is: for counter=initial value : increment : final value statements; end Note: Matlab array index always starts from 1, not from 0 like C language. example: N=1000; tic A = zeros(N); for k=1:N for l=1:N A(k,l) = sin(k)*cos(l); end end toc

Syntax of the while loop is: while expression Statement end Syntax of if-else operation is: if expression1 statements (if expression1 is true) elaseif expression2 statements (if expression2 is true) else statements(if all previous expressions evaluated to false) end Example: %Initialise clear all clc fprintf('\n\n Input Shape'); fprintf('\n "c" for Circle \n "r" for Rectangle \n\n'); shape=input('shape>','s'); %Area calculation if shape=='c' radius = input('\n Enter radius'); area=pi*(radius^2); fprintf('\ Circle'); fprintf('\n Radius = %8.3f',radius); else height=input('\nEnter height'); width=input(' width'); area=height*width; fprintf('\n Rectangle'); fprintf('\n height = %8.3f', height); fprintf('\n width = %8.3f', width); end fprintf('\n Area = %8.3f',area);

Question: What is the job of ; after every line?


Plotting Example: x = pi/100:pi/100:10*pi; y = sin(x)./x; plot(x,y,r); MATLAB has several colours you can use to plot graphs: y yellow m magenta c cyan r red g green b blue w white k black Note: For BER Vs SNR plotting we use semilogy() to plot Y-axis in logarithmic scale.

Subplot example: % Several plots of the rational function y = x/(1+x^2) % in the same window. k = 0; for n=1:3:10 n10 = 10*n; x = linspace(-2,2,n10); y = x./(1+x.^2); k = k+1; subplot(2,2,k) plot(x,y,'r') title(sprintf('Graph %g. Plot based upon n = %g points.' ... , k, n10)) xlabel('x') ylabel('y') axis([-2,2,-.8,.8]) grid pause(2); end
Graph 1. Plot based upon n = 10 points. Graph 2. Plot based upon n = 40 points. 0.5 0.5

-0.5 -2 -1 0 x 1 2

-0.5 -2 -1 0 x 1 2

Graph 3. Plot based upon n = 70 points.

Graph 4. Plot based upon n = 100 points.

0.5

0.5

-0.5 -2 -1 0 x 1 2

-0.5 -2 -1 0 x 1 2

User-defined Functions The first line of a function.m file should like this: function [output1,output2,output3,] = function_name(input1,input2,) To call a user-defined function from a main program file is identical to calling a predefined Matlab function, simply type the function name followed by its corresponding input parameters. Example: function y = avg1(x) y = sum(x)/length(x); end Simulation Tips: Plot FER/BER versus p or Eb/N0 curves: When you obtain the simulated data for FER/BER, you usually need to plot them in a figure. Since FER/BER generally varies in a large range, we should plot them in a logarithm scale instead of a linear scale.

For FER/BER versus Eb/N0 curves, the horizontal axis Eb/N0 should be plotted in linear scale because it is usually expressed in the unit of dB. The vertical axis FER/BER should be plotted in logarithm scale. In Matlab, this can be done by the following function: semilogy(FER,Eb_N0_dB,); For FER/BER versus p (BSC channel) curves, you might find it appropriate to plot both axes in logarithm scale, which can be achieved by the following: loglog(FER,p,); How many blocks/frames to simulate in order to get a smooth curve? We are using simulation as a method to estimate the FER/BER according to FER number error of frames / total number of frames And BER number of error bits / total number of bits In order to get an accurate estimate, the number of error frames or the number of error bits needs to be large enough. As a rule of thumb, this number should be no smaller than 400. Otherwise, the estimates you obtain will be useless and the curves you plot will show big ripples. This means that for EACH Eb/N0 or p values you have to run the simulation until 400 or more bit errors are encountered. However, for a complex coding system, such as turbo codes and LDPC codes, due to the complexity of the encoder/decoder algorithms, at high SNR range, 400 errors might take a very long time (tens or hundreds of hours) to complete. In that case, in this project you can reduce the number to 100 for time saving. How to select the p or Eb/N0 range to simulate? The rule to choose the proper range of p or Eb/N0 is to ensure that the FER/BER is acceptable. Usually, for a coded system, the BER range of interest is 101 to 106. However, to simulate a codec system down to BER= 106 might take too long a time. Therefore, in this project, you can choose BER range from 101 to 104 or 105. Of course, if you have wrote an efficient program, you can option to simulate lower BERs. With the chosen range, you need to take samples in this range to simulate. For instance, if an Eb/N0 range of 0 to 5 dB is chosen, you might select 0 dB, 1 dB, 2 dB, 3 dB, 4 dB, 5 dB as the simulation points. However, this even selection might not be appropriate. For example, in the following curve, it is ok to choose 0,1,2,3,4,5dB, but after 5dB, the curve drops abruptly, you need to choose smaller steps to capture the transition region between 5 to 7dB. We can do the simulation in two steps. First choose an even sparse SNR samples to simulate, and hence identify the transition regions. Then select dense samples in the transition regions to do a fine simulation. BPSK Simulation with AWGN Channel: % BPSK Plotting Demonstration % This demo runs a very simple uncoded communications system using BPSK % modulation and plot its FER and BER curves % If any function is unfamiliar to you, type 'help function_name' % in the Matlab command window to get help clear all; % clear memory and workspace n=64; % frame length (number of bits per frame) Eb_N0_dB=0:6; % Eb/N0 (dB), the SNR MIN_FRM_ERRS=400; % minimum number of frame errors before simulation stops MIN_BIT_ERRS=400; % minimum number of bit errors before simulation stops Eb_N0=10.^(Eb_N0_dB/10); % convert to linear unit

% noise power, assuming signal power=1 % for BPSK, signal_power/noise_power=2Eb/N0 noise_power = 1./(2*Eb_N0); % allocate the memory for FER estimates fer_sim = zeros(1,length(Eb_N0)); % allocate the memory for BER estimates ber_sim = zeros(1,length(Eb_N0)); % run the simulation for each Eb/N0 for ii = 1:length(Eb_N0) bit_err_cnt = 0; % bit error counter frm_err_cnt = 0; % frame error counter frm_cnt = 0; % frame counter %simulatoin runs until the number of erroneous frames reaches MIN_FRM_ERRS while frm_err_cnt < MIN_FRM_ERRS | bit_err_cnt < MIN_BIT_ERRS % generate a message frame. 1 by n row vector. binary message. Msg = randint(1,n,2); % BPSK modulation tx_syms = 2*msg-1; % 0=> -1, 1=> +1 % AWGN channel rx_syms = tx_syms+wgn(1,n,noise_power(ii),'linear'); % BPSK demodulate dec_bits = double(rx_syms>0); % compare the transmitted and received sequences [bit_errs,dummy_ber] = biterr(msg,dec_bits); % count the bit errors bit_err_cnt=bit_err_cnt+bit_errs; % if at least one bit is in error, the whole frame is counted as error if bit_errs>0 frm_err_cnt=frm_err_cnt+1; end % count the frames frm_cnt=frm_cnt+1;

end

% estimate the frame error probability (FER) fer_sim(ii)=frm_err_cnt/frm_cnt; % estimate the bit error probability (BER) ber_sim(ii)=bit_err_cnt/(frm_cnt*n);

end

% calculate the theoretical BER = Q(sqrt(2Eb/N0)) % Q(x)=erfc(x/sqrt(2))/2; BER_theor=erfc(sqrt(Eb_N0))/2; % calculate the theoretical FER = 1-(1-BER)^n FER_theor=1-(1-BER_theor).^n; % plot the curves figure; % open a new figure window

% plot the simulated FER curve with logarithmic y axis semilogy(Eb_N0_dB,fer_sim,'bx-'); hold on; % hold the figure so the next plot will not overwrite it semilogy(Eb_N0_dB,FER_theor,'ks--'); % plot the theoretical curve xlabel('Eb/N0 (dB)'); % x axis label ylabel('FER'); % y axis label legend('simulated','theoretical'); % the curves' lengend % open another figure window for BER figure; semilogy(Eb_N0_dB,ber_sim,'bx-'); hold on; semilogy(Eb_N0_dB,BER_theor,'ks--'); xlabel('Eb/N0 (dB)'); ylabel('BER'); legend('simulated','theoretical'); The BER Vs Eb/N0 may look like following figure:
10
-1

simulated theoretical
-2

10

10 BER 10

-3

-4

10

-5

10

-6

5 Eb/N0 (dB)

10

Binary Symmetric Channel demonstration % % % % Binary Symmetric Channel (BSC) Demonstration This demo runs a very simple uncoded communications system If any function is unfamiliar to you, type 'help function_name' in the Matlab command window to get help

clear all; % clear memory and workspace n=64; % frame length (number of bits per frame) perr=1e-2; % BSC channel error probability (transition probability) MIN_FRM_ERRS=100; % minimum number of frame errors before simulation stops bit_err_cnt=0; % bit error counter frm_err_cnt=0; % frame error counter frm_cnt=0; % frame counter % simulatoin runs until the number of erroneous frames reaches MIN_FRM_ERRS % while frm_err_cnt<MIN_FRM_ERRS % generate a message frame. 1 by n row vector. binary message. tx_bits=randint(1,n,2); % BSC channel [rx_bits,ch_errs]=bsc(tx_bits,perr);

% compare the transmitted and received sequences [bit_errs,dummy_ber]=biterr(tx_bits,rx_bits); % count the bit errors bit_err_cnt=bit_err_cnt+bit_errs; % if at least one bit is in error, the whole frame is counted as error if bit_errs>0 frm_err_cnt=frm_err_cnt+1; end % count the frames frm_cnt=frm_cnt+1;

end % print out the simulated frame error probability (FER) and bit error probability fprintf('SimulatedFER=%e \tBER=%e\n',frm_err_cnt/frm_cnt,bit_err_cnt/(frm_cnt*n)); % print out the theoretical values fprintf('Theoretical FER=%e \tBER=%e\n',1-(1-perr)^n,perr); % the theoretical BER should equal to perr because of no coding % the theoretical FER = 1-(1-perr)^n, why?

You might also like