Dsp
Dsp
The fscanf and fprintf commands behave like C scanf and printf functions. They support the following
format codes –
Basic Matlab, Prepared by, Abu Saleh Musa Miah, Lecturer-CSE Department, BAUST Page 1
BAUST, DSP Lab Day-1 2019
VARIABLES
[]
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.
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
MATLAB FUNCTIONS
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
'
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
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.
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)
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])
>> t = 10;
>> g = 9.8;
>> v0 = 50.75;
>> theta0 = 5*pi/12;
>> y0 = 0;
>> x0 = 0;
Using MATLAB, we want to generate samples of x(t) at time instances 0:0.01:1. We will discuss three approaches.
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
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])
Code Color
w White
k Black
b Blue
r Red
c Cyan
g Green
m Magenta
y Yellow
Excersize-3
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);
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>
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)
Exercise-4
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
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
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;
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
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