0% found this document useful (0 votes)
5 views

Dsp

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Dsp

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

Bangladesh Army University of Science and Technology (BAUST)

BAUST, DSP Lab Day-1


CSE-4204 Digital Signal Processing 2019
Day-1
Subject: Basic Matlab Command
GETTING STARTED:
>> command;
 Means an instruction command has been issued at the MATLAB prompt.
 If a semicolon (;) is placed at the end of a command, then all output from that command is
suppressed.
 Multiple commands can be placed on the same line, separated by semicolons;.
 Comments are marked by the percent sign (%),

>> help command;


 provide information on the inputs, outputs, usage, and functionality
of the command
>>clc - clears all input and output from the Command Window display, giving you a clean \
screen.
 clear - clears all functions and variables from memory.
 home – moves the cursor to the upper left corner of the window.
 quit - quits Matlab, although you can always do it the amateur way.
 marks (,, ;, :, etc.) have special meanings.
 1.23 is represented as simply 1.23
 While the real number 4.56 × 107 can be written as 4.56e7.
 The imaginary number √−1 is denoted either by 1i or 1j,
 We will use the symbol 1j.
 The complex number whose real part is 5 and whose imaginary part is 3 will be written as 5+1j*3.
 Other constants preassigned by MATLAB are pi for π,
 inf for ∞, and NaN for not a number (for example, 0/0).
 These preassigned constants are very important and, to avoid confusion, should not be redefined by users.

Input Output Command


Command Purpose
disp Displays contents of an array or string.
input Displays prompts and waits for input.
fscanf Read formatted data from a file.
fprintf

The fscanf and fprintf commands behave like C scanf and printf functions. They support the following
format codes –

Format Code Purpose


%s Format as a string.
%d Format as an integer.
%f Format as a floating point value.
Format as a floating point value in scientific
%e
notation.
%g Format in the most compact form: %f or %e.
\n Insert a new line in the output string.
\t Insert a tab in the output string.

cat Concatenates arrays.


find Finds indices of nonzero elements.
length Computes number of elements.
linspace Creates regularly spaced vector.

Basic Matlab, Prepared by, Abu Saleh Musa Miah, Lecturer-CSE Department, BAUST Page 1
BAUST, DSP Lab Day-1 2019

logspace Creates logarithmically spaced vector.


max Returns largest element.
min Returns smallest element.
prod Product of each column.
reshape Changes size.
size Computes array size.
sort Sorts each column.
sum Sums each column.
eye Creates an identity matrix.
ones Creates an array of ones.
zeros Creates an array of zeros.
cross Computes matrix cross products.
dot Computes matrix dot products.
det Computes determinant of an array.
inv Computes inverse of a matrix.

VARIABLES

In MATLAB, which stands for MATrix LABoratory,

a. Matrix: A matrix is a two-dimensional set of numbers arranged in rows and columns.


Numbers can be real- or complex-valued.
b. Array: This is another name for matrix.
The following are four types of matrices (or arrays):

• Scalar: This is a 1 × 1 matrix or a single number that is denoted by


the variable symbol, that is, lowercase italic typeface like a=a 11

• Column vector: This is an (N × 1) matrix or a vertical arrangement


of numbers. It is denoted by the vector symbol, that is,
lowercase bold typeface like

[]
x 11
x
x=[ x i 1 ]i: 1 …. N = 12
.
x 13
A typical vector in linear algebra is denoted by the column \
vector.

 Row vector: This is a (1 ×M) matrix or a horizontal arrangement of


Numbers. It is also denoted by the vector symbol, that is,
y= [ y 1 j ] j=1 ,… ., M =[ y 11 y 12 . .. . y 1 M ]

A one-dimensional discrete-time signal is typically represented


By An array as a row vector.

 General matrix: This is the most general case of an (N ×M) matrix


and is denoted by the matrix symbol, that is, uppercase
bold typeface like

This arrangement is typically used for two-dimensional discrete-time signals or images.

MATLAB does not distinguish between an array and a matrix except for operations. The following assignments denote
indicated matrix types in MATLAB:

a = [3] is a scalar,
x = [1,2,3] is a row vector,
y = [1;2;3] is a column vector, and
A = [1,2,3;4,5,6] is a matrix.

Basic Matlab, Prepared by, Abu Saleh Musa Miah, Lecturer-CSE Department, BAUST Page 2
BAUST, DSP Lab Day-1 2019

Exercise-1

1. Create a 5-by-1 column vector of zeros.


2. ,
L = 1 : 2 : 21
L = 1 3 5 7 9 11 13 15 17 19 21

3. Create a 6 x 1 vector a of zeros using the zeros command.


4. Create a row vector b from 325 to 405 with an interval of 20.
5. Use sum to find the sum a of vector b's elements.
6. Create two different vectors of the same length and add them.
a = [2, 1, 3]; b = [4 2 1]; c = a + b
7. Now subtract them. c=a-b
8. Perform element-by-element multiplication on them. c = a .* b
9. Perform element-by-element division on them. c = a ./ b
10. Raise one of the vectors to the second power. c = a .^ 2
11. Create a matrix of zeros with 2 rows and 4 columns

MATLAB FUNCTIONS

 zeros(M,N) for creating a matrix of all zeros,


 ones(M,N) for creating matrix of all ones,
 eye(N) for creating an N × N identity matrix, etc.
 rand(3, 5)
 magic(4)
 a = [9 8 7; 6 5 4; 3 2 1];
 b = [1 2 3; 4 5 6; 7 8 9];
 c = cat(3, a, b, [ 2 3 1; 4 7 8; 3 9 0])

OPERATORS

= assignment == equality
+ addition - subtraction or minus
* multiplication .* array multiplication
^ power .^ array power
/ division ./ array division
<> relational operators & logical AND
| logical OR ~ logical NOT
’ transpose .’ array transpose

ARRAY OPERATIONS

These operations treat matrices as arrays. They are also known as dot operations
because the arithmetic operators are prefixed by a dot (.), that is, .*, ./, or .^.
a) Array multiplication:
i. For it to be a valid operation, both arrays must be the same
size. Thus we have
1. x .∗y →1 D array
2. X.∗Y → 2 D array
b) Array exponentiation: In this operation, a scalar is raised to the power equal to every element in an array,
that is,

is an (N × 1) array,
whereas is an (N ×M) array.

Basic Matlab, Prepared by, Abu Saleh Musa Miah, Lecturer-CSE Department, BAUST Page 3
BAUST, DSP Lab Day-1 2019
MATRIX OPERATION

a) Matrix addition and subtraction: Array addition and subtraction. Two matrix operands be exactly the same
size.
b) Matrix conjugation: This operation is meaningful only for complex valued matrices. It produces
¿
i. Matrix in which all imaginary parts are negated. It is denoted by A in analysis and
ii. by conj(A) in MATLAB.
c) Matrix transposition: This is an operation in which every row (column) is turned into column (row). Let X
be an (N ×M) matrix
X = [ x ji ] ; j=1, … . , M , i=1 , … . , N
'

is an (M × N) matrix. To obtain just the transposition, we use the array operation of


conjugation, that is, A .' will do just the transposition.
d) Multiplication by a scalar:

e) Vector-vector multiplication: Let x be an (N × 1) and y be a (1 ×M) vectors. Then

f) Matrix-vector multiplication: If the matrix and the vector are compatible (i.e., the number of matrix-columns
is equal to the vector-rows), then this operation produces a column vector:

Exercise-2

12. Find the sum S of vector L’s elements


13. Form the matrix 2*4 matrix

14. Write a Matlab program that create 4*4 matrix that name is a,
15. Calculate sin(a)
16. Calculate the transpose of matrix a.

Matlab matrix and Vectors command Commands:

Basic Matlab, Prepared by, Abu Saleh Musa Miah, Lecturer-CSE Department, BAUST Page 4
BAUST, DSP Lab Day-1 2019

INDEXING OPERATIONS:

 x = [a:b:c], we can generate numbers from a to c in b increments. If b is positive (negative) then, we get
increasing (decreasing) values in the sequence x.
 The fragment x(a:b:c) accesses elements of x beginning with index a in steps of b and ending at c.

 Similarly, the : operator can be used to extract a submatrix from a matrix. For example, B = A(2:4,3:6) extracts
a 3×4 submatrix starting at row 2 and column 3.

 Another use of the : operator is in forming column vectors from row vectors or matrices.
 When used on the right-hand side of the equality (=) operator, the fragment x=A(:) forms a long column vector
x of elements of A by concatenating its columns.

 Similarly, x=A(:,3) forms a vector x from the third column of A. when used on the right-hand side of the =
operator, the fragment A(:)=x reformats elements in x into apredefined size of A.

PLOTTING
x = [0:5:100];
y = x;
plot(x, y)

x = [1 2 3 4 5 6 7 8 9 10];
x = [-100:20:100];
y = x. ^2;
plot(x, y)

x = [-100:5:100];
y = x. ^2;
plot(x, y)

17. Let us draw the graph of two polynomials


x = [-10 : 0.01: 10];

y=f(x) = 3x4 + 2x3+ 7x2 + 2x + 9 and


z=g(x) = 5x3 + 9x + 2

18. To create two-dimensional line plots, use the plot function.


For example, plot the value of the sine function from 0 to 2π:
T=0:2*pi;

clear;
clc;
t=0:0.001:2*pi;
y=sin(2*pi*t);
plot(t,y,'g^')

Basic Matlab, Prepared by, Abu Saleh Musa Miah, Lecturer-CSE Department, BAUST Page 5
BAUST, DSP Lab Day-1 2019

x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y
19. You can label the axes and add a title.
F=2;
A=5

t= [0:0.01:10];
y = A*sin(2*pi*t*F);
plot(t,y,’r*’);
xlabel('t')
ylabel('sin(t)')
title ('Plot of the Sine Function')
grid on
axis ([-5 10 -7 7])

plot(x, y), xlabel('x'), ylabel('Sin(x)'), title('Sin(x) Graph'),


grid on, axis equal

20. Plot cos(x) for above formula.

21. Plot a graph for

>> t = 10;
>> g = 9.8;
>> v0 = 50.75;
>> theta0 = 5*pi/12;
>> y0 = 0;
>> x0 = 0;

22. Create a script file and type the following code −


x = [0 : 0.01: 10];
y = exp(-x).* sin(2*x + 3);
plot(x, y), axis([0 10 -1 1])

23. Consider the following sum of sinusoidal functions.


t = [0 : 0.01: 2];

Using MATLAB, we want to generate samples of x(t) at time instances 0:0.01:1. We will discuss three approaches.

24. Let us generate two plots −

y = e−1.5xsin(10x)
y = e−2xsin(10x)
x = [0:0.01:5];

Command Purpose
axis Sets axis limits.
fplot Intelligent plotting of functions.

Basic Matlab, Prepared by, Abu Saleh Musa Miah, Lecturer-CSE Department, BAUST Page 6
BAUST, DSP Lab Day-1 2019

grid Displays gridlines.


plot Generates xy plot.
print Prints plot or saves plot to a file.
title Puts text at top of plot.
xlabel Adds text label to x-axis.
ylabel Adds text label to y-axis.
axes Creates axes objects.
close Closes the current plot.
close all Closes all plots.
figure Opens a new figure window.
gtext Enables label placement by mouse.
hold Freezes current plot.
legend Legend placement by mouse.
refresh Redraws current figure window.
set Specifies properties of objects such as axes.
subplot Creates plots in subwindows.
text Places string in figure.
bar Creates bar chart.
loglog Creates log-log plot.
polar Creates polar plot.
Creates semilog plot. (logarithmic
semilogx
abscissa).
Creates semilog plot. (logarithmic
semilogy
ordinate).
stairs Creates stairs plot.
stem Creates stem plot.

Basic 1D and more Plot Commands


length Length of vector or largest array dimension
ndims Number of array dimensions
numel Number of array elements
size Array dimensions
iscolumn Determines whether input is column vector
isempty Determines whether array is empty
ismatrix Determines whether input is matrix
isrow Determines whether input is row vector
isscalar Determines whether input is scalar
isvector Determines whether input is vector
diag Diagonal matrices and diagonals of matrix
flipdim Flips array along specified dimension
fliplr Flips matrix from left to right
flipud Flips matrix up to down
ipermute Inverses permute dimensions of N-D array
permute Rearranges dimensions of N-D array
repmat Replicates and tile array
reshape Reshapes array
sort Sorts array elements in ascending or descending order
sortrows Sorts rows in ascending order
squeeze Removes singleton dimensions
transpose Transpose

figure Creates a figure window to which MATLAB directs graphics output. An existing figure window
can be made current using the command figure(n), where n is the figure number specified in the
figure's title bar.
plot(x,y,'s') Generates a plot of y w.r.t. x with color, line style and marker specified by the character string s.
For example, plot(x,y,'c:+') plots a cyan dotted line with a plus marker at each data point. The
string s is optional and default values are assumed if s is not specified. For default values, list of
available colors, line styles, markers and their

Basic Matlab, Prepared by, Abu Saleh Musa Miah, Lecturer-CSE Department, BAUST Page 7
BAUST, DSP Lab Day-1 2019
corresponding character representations, type help plot.
plot(x,y1,x,y2, Creates a multiple plot of y1 vs. x, y2 vs. x and so on, on the same _g-
...) ure. MATLAB cycles through a predefined set of colors to distinguish
between the multiple plots.
axis([xmin,xmax Specifies axis limits for the x- and y- axes. This command is optional and by default MATLAB
, determines axes limits depending on the range of data used in plotting.
ymin,ymax])
title('...') Adds a title to the graph in the current figure window. The title is specified as a string within
single quotes.
xlabel('...') Adds a label to the x-axis of the graph in the current figure window This is again specified as a
string within single quotes.
ylabel('...') Similar to the xlabel command.
grid on Adds grid lines to the current axes.
grid off Removes grid lines from the current axes.
hold on This is used to add plots to an existing graph. When hold is set to
on, MATLAB does not reset the current _gure and any further plots
are drawn in the current _gure
hold off This stops plotting on the same _gure and resets axes properties to
their default values before drawing a new plot.
legend Adds a legend to an existing _gure to distinguish between the plotted
curves.
ezplot('f(x)', Plots the function represented by the string f(x) in the interval x0 _ x _ xn.
[x0,xn])

Setting Colors on Graph


MATLAB provides eight basic color options for drawing graphs. The following table shows the colors and
their codes −

Code Color

w White

k Black

b Blue

r Red

c Cyan

g Green

m Magenta

y Yellow

Excersize-3

24. Plot the following equation:

25. Plot the following command:


a) Using the plot command for multiple plots, plot y = atan(x) and y = acot(x) on the same graph for values of x
de_ned by x = -pi/2:pi/30:pi/2.

c) Using the plot command for a single plot and the hold commands, plot y = atan(x) and y = acot(x) on the same
graph for values of x de_ned by x = -pi/2:pi/30:pi/2.

c) Using the ezplot command, plot y = 2 3 sin(9_x), for values of x such that 0 <= x <= 2*pi.

CONTROL-FLOW

Basic Matlab, Prepared by, Abu Saleh Musa Miah, Lecturer-CSE Department, BAUST Page 8
BAUST, DSP Lab Day-1 2019
a. If-else:
if condition1
command1
elseif condition2
command2
else
command3
end

b. for..end loop:
for index = values
program statements
:
End

EXAMPLE 1.1

for i = a:b The for loop repeats statements a speci_c number of times, starting
with i = a and ending with i = b, incrementing i by 1 each iteration
of the loop. The number of iterations will be b - a + 1.
while condition The while loop repeats statements an inde_nite number of times as
long as the user-de_ned condition is met.
for i = a:h:b The for loop works exactly the same except that i is incremented by
h after each iteration of the loop.
clear Clears all previously de_ned variables and expressions.
fprintf Outputs strings and variables to the Command Window. See below
for an example.
abs(x) Returns the absolute value of the de_ned variable or expression x.
factorial(n) Returns the factorial of the de_ned variable or expression n. The ellipses can
be used to break up long lines by providing a contin-
uation to the next line. Strings must be ended before the ellipses but
can be immediately restarted on the next line. Examples below show
this.

fprintf:
This is an example of how to use fprintf to display text to the command window.
fprintf ('\nOrdinary Differential Equations are not so ordinary.\n');
fprintf ('-------------------------------------------------------'...'----------------\n');
fprintf ('This course is CME %g: ODEs for Engineers. My expected'...' grade is %g\n',102,100);
x = 100; y = 96;
fprintf ('The previous course was CME %g: Vector Calculus for '...'Engineers. My grade was: %g\n',x,y);

SCRIPTS AND FUNCTIONS

The M Files
 Scripts − script files are program files with .m extension. In these files, you write series of
commands, which you want to execute together. Scripts do not accept inputs and do not return any
outputs. They operate on data in the workspace.
 Functions − functions files are also program files with .m extension. Functions can accept inputs and
return outputs. Internal variables are local to the function.

The second construct of creating a block of code is through subroutines. These are called
functions, which also allow us to extend the capabilities of MATLAB.

edit
Or
edit <filename>

mkdir progs % create directory progs under default directory


chdir progs % changing the current directory to progs
edit prog1.m % creating an m file named prog1.m

Basic Matlab, Prepared by, Abu Saleh Musa Miah, Lecturer-CSE Department, BAUST Page 9
BAUST, DSP Lab Day-1 2019

• Functions:
function max = mymax(n1, n2, n3, n4, n5)

%This function calculates the maximum of the


% five numbers given as input
max = n1;
if(n2 > max)
max = n2;
end
if(n3 > max)
max = n3;
end
if(n4 > max)
max = n4;
end
if(n5 > max)
max = n5;
end

Exercise-4

Symbols and Strings: Differentiation and Integration

syms x y z Declares variables x, y, and z as symbolic variables.


26. Define the following function using syms:

syms x
f = x^2*exp(x) - 5*x^3;
27. Defne the following function using syms:

Basic Matlab, Prepared by, Abu Saleh Musa Miah, Lecturer-CSE Department, BAUST Page 10
BAUST, DSP Lab Day-1 2019

t = 0:0.1:10; % sample points from 0 to 2 in steps of 0.01


x = sin(2*pi*t); % Evaluate sin(2 pi t)
plot(t,x,’b’); % Create plot with blue line
xlabel(’t in sec’); ylabel(’x(t)’); % Label axis
title(’Plot of sin(2\pi t)’); % Title plo

hold on; % Create plot with blue line


Hs = stem(t ,x ,’g’,’filled’); % Stem-plot with handle Hs
set(Hs,’markersize’,6);
hold off; % Change circle size

The following set of commands displays a discrete-time sine function using these constructs
>> n = 0:1:40; % sample index from 0 to 20
>> x = sin(0.1*pi*n); % Evaluate sin(0.2 pi n)
>> Hs = stem(n,x,’b’,’filled’); % Stem-plot with handle Hs
>> set(Hs,’markersize’,4); % Change circle size
>> xlabel(’n’); ylabel(’x(n)’); % Label axis
>> title(’Stem Plot of sin(0.2 pi n)’); % Title plot

Plot a line on X-axis

t = [0:0.01:5];
y=zeros(size(t))
plot(t,y)

Load Data:
filename = 'smile.jpg';
A = importdata(filename);
image(A);
SunDay MonDay TuesDay WednesDay ThursDay FriDay SaturDay
95.01 76.21 61.54 40.57 55.79 70.28 81.53
73.11 45.65 79.19 93.55 75.29 69.87 74.68
60.68 41.85 92.18 91.69 81.32 90.38 74.51
48.60 82.14 73.82 41.03 0.99 67.22 93.18
89.13 44.47 57.63 89.36 13.89 19.88 46.60

Basic Matlab, Prepared by, Abu Saleh Musa Miah, Lecturer-CSE Department, BAUST Page 11
BAUST, DSP Lab Day-1 2019
Create a script file and type the following code in it –

filename = 'weeklydata.txt';
delimiterIn = ' ';
headerlinesIn = 1;
A = importdata(filename,delimiterIn,headerlinesIn);

% View data
for k = [1:7]
disp(A.colheaders{1, k})
disp(A.data(:, k))
disp(' ')
end

Example
We have a text data file 'myfile.txt' saved in our working directory. The file stores rainfall data for three months; June,
July and August for the year 2012

Rainfall Data
Months: June, July, August

M=3
12:00:00
June-2012
17.21 28.52 39.78 16.55 23.67
19.15 0.35 17.57 NaN 12.01
17.92 28.49 17.40 17.06 11.09
9.59 9.33 NaN 0.31 0.23
10.46 13.17 NaN 14.89 19.33
20.97 19.50 17.65 14.45 14.00
18.23 10.34 17.95 16.46 19.34
09:10:02
July-2012
12.76 16.94 14.38 11.86 16.89
20.46 23.17 NaN 24.89 19.33
30.97 49.50 47.65 24.45 34.00
18.23 30.34 27.95 16.46 19.34
30.46 33.17 NaN 34.89 29.33
30.97 49.50 47.65 24.45 34.00
28.67 30.34 27.95 36.46 29.34
15:03:40
August-2012
17.09 16.55 19.59 17.25 19.22
17.54 11.45 13.48 22.55 24.01
NaN 21.19 25.85 25.05 27.21
26.79 24.98 12.23 16.99 18.67
17.54 11.45 13.48 22.55 24.01
NaN 21.19 25.85 25.05 27.21
26.79 24.98 12.23 16.99 18.67

filename = '/data/myfile.txt';
rows = 7;
cols = 5;

% open the file


fid = fopen(filename);

% read the file headers, find M (number of months)


M = fscanf(fid, '%*s %*s\n%*s %*s %*s %*s\nM=%d\n\n', 1);

% read each set of measurements


for n = 1:M
mydata(n).time = fscanf(fid, '%s', 1);
mydata(n).month = fscanf(fid, '%s', 1);

% fscanf fills the array in column order,

Basic Matlab, Prepared by, Abu Saleh Musa Miah, Lecturer-CSE Department, BAUST Page 12
BAUST, DSP Lab Day-1 2019
% so transpose the results
mydata(n).raindata = ...
fscanf(fid, '%f', [rows, cols]);
end
for n = 1:M
disp(mydata(n).time), disp(mydata(n).month)
disp(mydata(n).raindata)
end

% close the file


fclose(fid);

There are two ways to export a numeric array as a delimited ASCII data file −
Using the save function and specifying the -ascii qualifier
Using the dlmwrite function
Syntax for using the save function is −
save my_data.out num_array -ascii
where, my_data.out is the delimited ASCII data file created, num_array is a numeric array and −ascii is the
specifier.
Syntax for using the dlmwrite function is −
dlmwrite('my_data.out', num_array, 'dlm_char')

num_array = [ 1 2 3 4 ; 4 5 6 7; 7 8 9 0];
save array_data1.out num_array -ascii;
type array_data1.out
dlmwrite('array_data2.out', num_array, ' ');
type array_data2.out

h = 'hello';
save textdata.out h -ascii
type textdata.out

Basic Matlab, Prepared by, Abu Saleh Musa Miah, Lecturer-CSE Department, BAUST Page 13

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy