Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
39 views

Lab Sheet 00 Introduction To MATLAB

The document provides an introduction to MATLAB including how to use the command window, plot graphs, write functions and scripts, and perform basic operations. It covers various MATLAB commands and programming concepts like conditional statements, loops, and complex numbers.

Uploaded by

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

Lab Sheet 00 Introduction To MATLAB

The document provides an introduction to MATLAB including how to use the command window, plot graphs, write functions and scripts, and perform basic operations. It covers various MATLAB commands and programming concepts like conditional statements, loops, and complex numbers.

Uploaded by

SREELEKHA K R
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

19ECE284 Digital Signal Processing Lab

Ex.No: 0
Ex.Name: Introduction to MATLAB
Name of the student: Reg.No:
Objective:
1. To get familiar with MATLAB
2. To Understand commands and syntax of MATLAB.
3. To write a simple code for a given problem in MATLAB.
Introduction
MATLAB is a high-performance language for technical computing. It integrates computation,
visualization, and programming in an easy-to-use environment where problems and solutions
are expressed in familiar mathematical notation. The name MATLAB stands for matrix
laboratory. MATLAB was originally written to provide easy access to matrix.
Desktop Tools
Command Window: Use the Command Window to enter variables and run functions and M-
files. Command History: Statements you enter in the Command Window are logged in the
Command History. In the Command History, you can view previously run statements, and
copy and execute selected statements.
Current Directory Browser: MATLAB file operations use the current directory reference
point. Any file you want to run must be in the current directory or on the search path.
Workspace: The MATLAB workspace consists of the set of variables (named arrays) built up
during a MATLAB session and stored in memory.

To get associated with the MATLAB command window and commands, type the
following commands at the prompt.
(a) x=3
This command will set a variable named x equal to a 1x1 matrix with the value 3 in it.
If x already existed, its previous contents are destroyed and replaced with the new
19ECE284 Digital Signal Processing Lab

matrix; otherwise, MATLAB will create a new variable called x and start from scratch.
Regardless, x will be [3] when this command is finished.
(b) x=3;
Note that the semi-colon suppresses MATLAB’s display response to any command.
This is used when the user does not care to have MATLAB display a response to the
command.
(c) x
A user is able to find the value of any variable simply by typing that variable’s name
into the command window.
(d) y=x+3
When assigning values to a variable, the user may implement already-defined variables
in the calculation for that variable. Given the formula above, y should now be equal to
6. You can check this by typing y into the command window. It is important to note
here that y is not created as a function of x - rather, it is created from calculations
including x. Regardless of future changes to the x variable, the y variable will remain
the same. To prove this, type x=10 and then y at the command prompt; y is still 6.
(e) y+3
If no assignment operator ( = ) is used, but MATLAB performs a calculation or is asked
to run a function that returns one or more variables, MATLAB will assign the
evaluation of the expression to a variable called ans. You can check to make sure that
the ans matrix contains 9 by typing ans at the command prompt.
Important note: MATLAB does not allow an index of zero into an array unless you are
performing logical indexing using a vector including a logical 0 and want to ignore the
corresponding element of the array into which you are indexing.

Matlab can be used as a calculator:


3+4*5
3^2
pi % reserved for pi
sqrt(9) % computes square root of 9
x = sqrt(9) % assigns output 3 to variable x
x^2 % x^2=3^2 should give 9
9^(1/2) % same as sqrt(9)
sin(pi) % note that we do not get exactly zero
log(4), exp(1) % computes logarithms and exponentials
x = exp(1); % semicolons at the end hide the output
x % prints the value of x
2*10^(-8), 2e-8 % one over 200million can be entered in various ways
19ECE284 Digital Signal Processing Lab

Matrices:
𝟏 𝟐 𝟑
𝑨 = ( 𝟒 𝟓 𝟔 ) can be entered as follows row by row (note the use of commas and
𝟏𝟎 𝟏𝟏 𝟏𝟐
semicolons to separate columns and rows):
A = [1,2,3; 4,5,6; 10,12,13]
Its columns and rows can be accessed using the colon operator which selects entire rows or
columns: A(:,1) % first column
A(3,:) % third row
A(1:2,:) % first and second row
A(3,2) % entry in 3rd row, 2nd column

Plotting:
x = [0,pi/4,pi/2,3*pi/4,pi]
y = sin(x) % compute the sine of each entry of x
plot(x,y) % a rather ragged graph of the sine function
y= x.^2 % compute x^2: note .^
plot(x,y) % plot x.^2
Now type “close all” in command window and observe what happened.

Plotting different waves in a same plot:


clear all
X = [3 9 27]; % dependent vectors of interest
Y = [10 8 6];
Z = [4 4 4];
t = [1 2 3]; % independent vector
plot(t, X, ‘blue’, t, Y, ‘red’, t, Z, ‘green’)
title(‘Plot of Distance over Time’) % title
ylabel(‘Distance (m)’) % label for y axis
xlabel(‘Time (s)’) % label for x axis
legend(‘Trial 1’, ‘Trial 2’, ‘Trial 3’)
legend(‘Location’,‘NorthWest’) % move legend to upper left
19ECE284 Digital Signal Processing Lab

Subplots
It can sometimes be useful to display multiple plots on the same figure for comparison. This
can be done using the subplot function, that takes arguments for number of rows of plots,
number of columns of plots, and plot number currently being plotted:
Example:
clear all
close all
x=0:.1:2*pi; % x vector from 0 to 2*pi
subplot(2,2,1); %subplot (nrows,ncols,plot_number),
%plot sine function
plot(x,sin(x));
subplot(2,2,2);
% plot cosine function
plot(x,cos(x));
subplot(2,2,3)
% plot negative exponential function
plot(x,exp(-x));
subplot(2,2,4); % plot x^3
plot(x, x.^3);

Conditional Statements:
For Loop

for index = values


<program statements>
...
end

Example:
for a = 10:20
disp(a)
end
19ECE284 Digital Signal Processing Lab

Output:
10

11

12

13

14

15

16

17

18

19

20

While Statement
The while statement is like the for statement except that execution stops when a logic
expression is satisfied.
n=1;
while 2*n<5000; n=2*n;end;
n = 4096 %compute the largest power of 2 that is less than 5000.
If Statement
The if statement permits us to execute statements selectively depending on the outcome of a
logic expression.
Syntax:

if <expression>

<commands>…%executed only when

%expression is true

end
19ECE284 Digital Signal Processing Lab

Example:
x = 4;

if x<0

disp(‘x is negative’)

else

disp(‘x is positive’)

end

Answer: x is positive

Creating Function in MATLAB


function [y1,...,yN] = myfun(x1,...,xM)
declares a function named myfun that accepts inputs x1,...,xM and returns outputs y1,...,yN.
This declaration statement must be the first executable line of the function. Valid function
names begin with an alphabetic character, and can contain letters, numbers, or underscores.
Example 1: Write a function to calculate the average of given array.
function ave = average_calculation(x)
ave = sum(x(:))/length(x);
end

>> x=[1 2 3 4]
>> average_calculation(x)
>> ans
=4
Example2 : Write a function to calculate the mean and standard deviation of x
function [m,s] = stat(x)
n = length(x);
m = sum(x)/n;
s = sqrt(sum((x-m).^2/n));
end

>> x1 = [12.7, 45.4, 98.9, 26.6, 53.1];


[ave,stdev] = stat(x1)

>> ans
19ECE284 Digital Signal Processing Lab

ave =
47.3400
stdev =
29.4124

Complex numbers operation


Complex numbers in MATLAB are doubles with a real part and an imaginary part. The
imaginary part is declared by using the 'i' or 'j' character. For example, to declare a variable as
'1 + i' just type as following:

>> x = 1 + i
x = 1.000 + 1.000i

>> x = 1 + j
x = 1.000 + 1.000i

To remember

>> i = 1; %bad practise to use i as variable


>> a = 1 + i
a=2
>> x=complex(2,6)

ans =
2.0000 + 6.0000i
>>%Extract real number from the complex number vector x
>> real(x)
ans =
2
>>%Extract imaginary number from the complex number vector x
>> imag(x)

ans =
6
>> conj(x)

ans =
2.0000 - 6.0000i
>>%Extract absolute value of the complex number vector x
>> abs(x); % absolute value= √22 + 62
ans =
6.3246
19ECE284 Digital Signal Processing Lab

To find phase angle ,

>> angle(x)

ans =

1.2490

%rectangular to polar conversion


x=2+3j;
rho=abs(x)
theta=angle(x)
%Polar to rectangular conversion
x=rho*exp(j*theta)

Exercise 1: Evaluate the MATLAB expressions (Calculate them manually before doing
in MATLAB)

Exercise 2: Evaluate the MATLAB expressions.

𝒙𝟐
Exercise 3: Construct a function to compute 𝒚 = 𝒙𝟑 +𝟏 for the values of x from 1 to 3 with
the steps of 0.01.
19ECE284 Digital Signal Processing Lab

𝒙𝒄𝒐𝒔𝒙
Exercise 4: : Construct a function to compute 𝒚 = 𝒙𝟐 +𝟒𝒙+𝟏 for the values of x from 1 to 3
with the step size of 0.1.
Exercise 5: Write a MATLAB script to calculate the factorial of the given number using
For loop.

Exercise 6: Determine the sum of geometri expression ∑𝟔𝒏=𝟏 𝟐𝒏 using While.


Exercise 7:

You might also like