MATLAB programming language Tutorial

This MATLAB programming language tutorial basics of matlab, how to start and quit matlab,flow control,matrices,arrays,arithmetic operators,matrix operations,load function,save function,plotting functions,script and functions in matlab and sample matlab program.

MATLAB INTRODUCTION

This section covers basics of matlab including Benefits of MATLAB and Applications of MATLAB.

Basics of MATLAB

MATLAB is scientific numerical analysis programming language. It is widely used for mathematical algorithm development requiring complex operations. It is developed by Mathworks Inc.(www.mathworks.com?) The beauty of matlab is matrix operations, data manipulation and plotting and interfacing with other programming languages (FORTRAN, java, c, c++). GUI can also be built with the help of matlab GUI tools for easy user interaction with backend matlab code. In this matlab programming tutorial we will go through matlab programming syntax and sample matlab program.

MATLAB WORK ENVIRONMENT

This section covers how to start and quit matlab,load/save operation,plots/figures, Script and functions,Creating and working with arrays, vectors, matrices.

How to start and quit MATLAB

>>One can start MATLAB either using shortcut icon created during installation or from program files. Once MATLAB opens, window with following sub windows get open.
1. Command window
2. Workspace
3. Command history
4. Menu/icons

>>To exit MATLAB, type quit In the command window or go to File> EXIT MATLAB .

Load/save operation

>> To save matlab workspace variables having .mat extension use either of following.

File > Save OR
Save function
>> To save in any other format use proper extension other than .mat such as .dat
Syntax for Save function:
save filename -> Used to save all the workspace variable to the file specified by filename
save filename var1 var2 -> used to save var1 and var2 to the file 'filename'
save ... option -> Used to save with option as specified.

>> To load matlab variables from a file to the matlab workspace use either of following.

File > Import Data OR
load function
Syntax for load function:
load filename -> loads all the variables from the file to matlab workspace.
load filename X Y Z ->loads variables X,Y and Z from the file to the matlab.

Plots and figures,Creating simple 2D plots

>> figure and plot are the functions used for plotting variables on x, y, z co-ordinates based on need.
>> plot is used for 2D plotting and plot3 is used for 3D plotting.
>>'mesh' and 'meshc' are useful functions for plotting in 3D.

Script and functions

There are two ways .m files are created for different application. Script is the set of commands stored as .m file and will execute all the commands stored in the sequence when user calls the m file with its name. Script does not take or return any arguments and operate mainly on the data available in matlab workspace. Matlab Function can take and return arguments. Local variables are also defined which will be local to the respective function. Global variables can be defined in main.m file. Just type 'help' in the command prompt or 'help function_name' to get detailed description of the command or function to use.

OPERATORS AND BUILT-IN FUNCTIONS

This section covers Arithmetic Operators,Relational Operators,Logical Operators,Built-in-functions,Input and Output in MATLAB

Arithmetic Operators:

+ Add
- Subtract
* Multiply
/ Divide
\ Left division
^ Power or exponent
' Complex conjugate transpose
( ) Evaluation Order in a expression

Relational Operators:

< Less than
<= Less than oe equal
> Greater than
>= Greater than or equal
== Equal
~= Not equal

Logical Operators:

& Logical AND
| Logical OR
~ Logical complement(NOT)
xor Exclusive OR

Built-in-functions:

There are built in matlab functions for various matrix operations.
reshape
sum
rot90
transpose
diag
fliplr
flipud
Refer following link from MathWorks Inc to know many such functions provided in MATLAB.
https://www.mathworks.in/help/matlab/functionlist.html

CONTROL FLOW IN MATLAB

This section covers While loop,If-else if-else statement and for loop.

if statement

if cond=1
M = sum(a,b)
elseif cond=2
M = multiply(a,b)
else
M = divide(a,b)
end

switch statement

switch (cond)
case 1
M = sum(a,b)
case 2
M = multiply(a,b)
case 3
M = divide(a,b)
otherwise
error('This is impossible')
end

for loop

for i = 1:m
for j = 1:n
H(i,j) = 1/(i+j);
end
end

while statement

i=0;
while cond1 > cond2
i= i+1;
end

continue and break statements are also used similarly as they are used in C programming language.

MATRICES AND VECTORS

This section covers creating matrices and vectors,Indexing matrices,initializing and reshaping and Manipulation of matrices.

Matrices and Array

A = [1 2 3; 5 6 7; 9 10 11; 13 14 15];
Will store A as matrix in the matlab workspace and is 4 x 4 matrix(4 rows and 3 columns) will be as shown below.
1   2     3
5    6     7
9     10    11
13    14    15

A(i,j) will extract ith row and jth column element.
For example A(2,2) equals 6.
A(:,1) represent all the rows of 1st column.
A(2:3,2) represent 2nd and 3rd rows of the 2nd column.
Matrix with single row is called as array. Following is the example of Array A with 5 elements.
A=[1 2 3 4 5];

Matrix operations

A+B - > Addition of two matrices
A-B -> Subtraction of two matrices
A*B -> Multiplication of two matrices
A.*B -> Multiplication of elements of two matrices
A/B -> Right Division of two matrices, Result of B/A is equal to the result of B*inv(A)
A./B -> Array Right Division, A and B should be of same size
A\B ->Left Division of two matrices, Result of A\B is equal to result of inv(A)*B,
A.\B -> Array Left Division, A and B should be of same size
x^P ->If x scalar and P matrix, x^P is x raised to the matrix power P using eigenvalues and eigenvectors. If both are matrices it will result in error.
A.^B -> Array power
A' -> Transpose of the matrix
A.' ->Array transpose

'length' and 'size' functions will give dimensions of the matrix/array.

STRUCTURE AND CELL in MATLAB

This section covers Creating/Manipulating structures and Creating/Manipulating cells.

A structure will have several fields, several fields will have different types of data. Single field must contain data of the same type.

We will see example of the structure by name 'Springsem' with fields course and score as shown below.

Springsem.course = 'MS';
Springsem.score = [70 80 90];
Type following at the command prompt will produce all the fields of the structure.
>>Springsem
Springsem =
course: 'MS'
score: [70 80 90]

A cell is the most versatile data object in MATLAB. It can contain any type of the data for example, array,strings,structures or cells. Let us create a cell as mentioned below.

C=cell(2,2); % create 2 by 2 cell
% cell(2) will do the same
C(1,1) = rand(2); % Put a 2x2 random matrix in the 1st box
C(1,2) = char('mohan','john'); % put a string array in the 2nd box
C(2,1) = Springsem; % put a structure in the 3rd box
C(2,2) = cell(2,2); % put a 2x2 cell in the 4th box

Sample Large matlab program

This section covers example of large MATLAB program using multiple m files

This program adds various impairments (awgn, frequency offset, Rayleigh channel and DC offset) to the ideal modulated data and plots constellation diagram.
main.m -> Main matlab file
frequency_offset -> will incorporate frequency offset to the input vector
wimax_mapping -> will convert input binary vector to the complex data output based on modulation scheme selected
Run the main.m file to see the results.

% -----------------------------------------------------main.m function------------------------------------------------ len=input('Enter the length of the payload:');
mod=input('Enter 1 for bpsk, 2 for qpsk, 4 for 16qam, 6 for 64qam:');
if mod==1
c1=sqrt(1);
elseif mod==2
c1=sqrt(1/2);
elseif mod==4
c1=sqrt(1/10);
elseif mod==6
c1=sqrt(1/42);
else printf('wrong entry');
end
%This part will generate binary vector as per length entered by user
data=floor(rand(1,len)+0.5);
%Mapping of binary data
mapper_out=wimax_mapping(data',mod,c1);
figure;plot(real(mapper_out),imag(mapper_out),'r+');title('ideal constellation');
%Adding AWGN
snr=input('Enter SNR:');
map_out_awgn=awgn(mapper_out,snr,'measured');
figure;plot(real(map_out_awgn),imag(map_out_awgn),'r+');title('constellation with Added AWGN');
%Adding Frequency Offset
foff=input('Enter Frequency offset:');%= 10e3; % Hz
foff=(foff)/20e6; % 20MHz is the Bandwidth of the system
map_out_foff=frequency_offset(mapper_out,foff);
figure;plot(real(map_out_foff),imag(map_out_foff),'r+');title('constellation with Frequency offset');
%Adding Rayleigh channel
choice=input('Enter 1 to apply the channel, other no. to bypass:');%10 Hz;sample time=0.1e-3;
if(choice==1)
ts=(256/4e6);
doppler=0.1;
tau=[0.0 0.4 0.9];
pdb=[0 -15 -20];
chan = rayleighchan(ts,doppler,tau,pdb);
%TS is the sample time of the input %0.1e-3;
%signal, in seconds. FD is the maximum Doppler shift, in Hertz. %100 Hz
map_out_chl=filter(chan,mapper_out);
figure;plot(real(map_out_chl),imag(map_out_chl),'r+');title('constellation with channel');
else
disp('no channel applied proceed to DC offset');
end
%Adding DC offset
DCO=input('Enter DC offset:'); %2.5;
%map_out_dc= (real(mapper_out)+DCO) +i*(imag(mapper_out)+DCO);
map_out_dc= mapper_out* DCO;
figure;plot(real(map_out_dc),imag(map_out_dc),'r+');title('constellation with DC offset');
% figure;plot(abs(fft(mapper_out,256)));title('spectrum ideal');
% figure;plot(abs(fft(map_out_dc,256)));title('spectrum with DC offset');
% ----------------------------frequency_offset.m function ------------------
function [d1] = frequency_offset(d1,CFO)
m = length(d1);
d1 = d1.*exp(i*2*pi*(0:m-1)*CFO);
%---------------------------- wimax_mapping.m function-----------------------
function [map_out]=wimax_mapping(data,mode,fact)

input_seq = data;

switch mode
case 1
b=fact*[1 -1];
case 2
b=fact*[1+1i -1+1i 1-1i -1-1i];
case 4
b=fact*[1+1i 1+3i 1-1i 1-3i 3+1i 3+3i 3-1i 3-3i -1+1i -1+3i -1-1i -1-3i -3+1i -3+3i -3-1i -3-3i];
case 6
b=fact*[3+3i 3+1i 3+5i 3+7i 3-3i 3-1i 3-5i 3-7i 1+3i 1+1i 1+5i 1+7i 1-3i 1-1i 1-5i 1-7i 5+3i 5+1i 5+5i 5+7i 5-3i 5-1i 5-5i 5-7i 7+3i 7+1i 7+5i 7+7i 7-3i 7-1i 7-5i 7-7i -3+3i -3+1i -3+5i -3+7i -3-3i -3-1i -3-5i -3-7i -1+3i -1+1i -1+5i -1+7i -1-3i -1-1i -1-5i -1-7i -5+3i -5+1i -5+5i -5+7i -5-3i -5-1i -5-5i -5-7i -7+3i -7+1i -7+5i -7+7i -7-3i -7-1i -7-5i -7-7i];
otherwise error('wrong choice');
end
count=1;
count1=1;
for i=1:(ceil(length(input_seq)/mode))
temp=0;
for j=1:mode
temp=bitor(temp,bitshift(input_seq(count),(j-1)));
count=count+1;
if(count>length(input_seq))
break;
end
end
map_out(count1)=b(temp+1);
count1=count1+1;
end

Useful Links to MATLAB Source codes

The MATLAB Source code Section on RF Wireless World site covers matlab coding on image processing, signal processing and communication domain.


OFDM MATLAB simulation code

Refer OFDM Tx Rx MATLAB Code➤ & MATLAB Source code section.

MORE LINKS to MATLAB SOURCE CODES:- PTS for PAPR reduction  OFDM Preamble generation  Time off estimation corr  Freq off estimation corr  channel estimation  11a WLAN channel  11g WLAN channel  15.3 UWB channel  15.4a UWB channel  16d SUI Channel  16e wimax channel  Rician channel  Rayleigh channel  SC-FDMA  PN sequence generation  3D plotting  AM FM PM modulation  OFDMA Tx Rx  AES DES  carrier aggregation  CCDF  FIR Filter  IIR Filter  Low Pass FIR  Viterbi decoder  CRC8 CRC32