Matrix Laboratory: Subject: Digital System Processing
Matrix Laboratory: Subject: Digital System Processing
SUBMITTED TO: Mrs. Ritu Pahwa Asst. Professor: DSP Deptt: ECE VCE, ROHTAK
INTRODUCTION TO
Sumit 514/EC/08
MATRIX LABORATORY
SCHEMATIC DIAGRAM OF MATLAB
Graphics Graphics * 2D
* 3D * Color and lightening * Animation * Audio and video
processing
INTRODUCTION
Topical Help: In addition to the help on individual functions, you can get help on any of the following topics by typing help topicname at the command line. Arith relop Punct Sumit Arithmetic operators Relational and logical operators Special character operators 514/EC/08
Slash Paren Precedence Datatypes Lists Strings function_handle Debug Java Fileformats changeNotification
Arithmetic division operators Parentheses, braces, and bracket operators Operator precedence MATLAB data types, their associated functions, and operators that you can overload Comma separated lists Character strings Function handles and the @ operator Debugging functions Using Java from within MATLAB A list of readable file formats Windows directory change notification
Keywords: MATLAB reserves certain words for its own use as keywords of the language. To list the keywords, type iskeyword ans = 'break' , 'case' , 'catch' , 'continue' , 'else' , 'elseif' , 'end' , 'for' , 'function' , 'global' , 'if' , 'otherwise' , 'persistent' , 'return' , 'switch' , 'try' , 'while' . Operators: The MATLAB operators fall into three categories: Arithmetic Operators perform numeric computations, for example, adding two numbers or raising the elements of an array to a given power. Relational Operators compare operands quantitatively, using operators like "less than" and "not equal to." Logical Operators use the logical operators AND, OR, and NOT. Arithmetic Operators: MATLAB provides these arithmetic operators: Operator + ../ ..' / Description Addition Right division Unary minus Transpose Matrix right division Operator .\ : ' \ Description Subtraction Left division Colon operator Complex conjugate transpose Matrix left division Operator * + ^ * ^ Description Multiplication Unary plus Power Matrix multiplication Matrix power
Relational Operators: MATLAB provides these relational operators: Operator < > == Description Less than Greater than Equal to Operator <= >= ~= Description Less than or equal to Greater than or equal to Not equal to
Logical Operators: MATLAB offers three types of logical operators and functions: Sumit 514/EC/08
1. Element-wise -- operate on corresponding elements of logical arrays. 2. Bit-wise -- operate on corresponding bits of integer values or arrays. 3. Short-circuit -- operate on scalar, logical expressions. The values returned by MATLAB logical operators and functions, with the exception of bit-wise functions, are of type logical and are suitable for use with logical indexing. Element-Wise Operators and Functions: The following logical operators and functions perform element-wise logical operations on their inputs to produce a like-sized output array. The examples shown in the following table use vector inputs A and B, where A = [0 1 1 0 1]; B = [1 1 0 0 1]; Operato Description Example r & Returns1 for every element location that is true (nonzero) in both A & B = 01001 arrays, and 0 for all other elements. | Returns 1 for every element location that is true (nonzero) in either A | B = 11101 one or the other, or both arrays, and 0 for all other elements. ~ Complements each element of the input array, A.~A = 10010 xor Returns 1 for every element location that is true (nonzero) in only one xor(A,B)=10100 array, and 0 for all other elements. Bit-Wise Functions: The following functions perform bit-wise logical operations on nonnegative integer inputs. Inputs may be scalar or in arrays. If in arrays, these functions produce a like-sized output array. The examples shown in the following table use scalar inputs A and B, where A = 28; % binary 11100 B = 21; % binary 10101 Function Description Example bitand Returns the bit-wise AND of two nonnegative integer bitand(A,B) = 20 arguments. (binary 10100) bitor bitcmp bitxor Returns the bit-wise OR of two nonnegative integer bitor(A,B) = 29 arguments. (binary 11101) Returns the bit-wise complement as an n-bit number, bitcmp(A,5) = 3 where n is the second input argument to bitcmp. (binary 00011) Returns the bit-wise exclusive OR of two nonnegative bitxor(A,B) = 9 integer arguments. (binary 01001)
Short-Circuit Operators: The following operators perform AND and OR operations on logical expressions containing scalar values. They are short-circuit operators in that they evaluate their second operand only when the result is not fully determined by the first operand. Operato r && Sumit Description Returns logical 1 (true) if both inputs evaluate to true, and logical 0 (false) if they do not. 514/EC/08
||
Returns logical 1 (true) if either input, or both, evaluate to true, and logical 0 (false) if they do not.
Program Control Statements: Program control is divided into these four categories: 1. Conditional Control -- if, switch 2. Loop Control -- for, while, continue, break 3. Error Control -- try, catch 4. Program Termination -- return 1. Conditional Control -- if, switch if, else, and elseif if evaluates a logical expression and executes a group of statements based on the value of the expression. In its simplest form, its syntax is if logical_expression statements end If the logical expression is true MATLAB executes all the statements between the if and end lines If the condition is false MATLAB skips all the statements between the if and end lines. switch, case, and otherwise switch executes certain statements based on the value of a variable or expression. Its basic form is switch expression (scalar or string) case value1 statements % Executes if expression is value1 case value2 statements % Executes if expression is value2 . . . otherwise statements % Executes if expression does not % match any case End 2. Loop Control -- for, while, continue, break for The for loop executes a statement or group of statements a predetermined number of times. Its syntax is for index = start:increment:end statements end Sumit 514/EC/08
The default increment is 1. You can specify any increment, including a negative one. For positive indices, execution terminates when the value of the index exceeds the end value; for negative increments, it terminates when the index is less than the end value. while The while loop executes a statement or group of statements repeatedly as long as the controlling expression is true (1). Its syntax is while expression statements end If the expression evaluates to a matrix, all its elements must be 1 for execution to continue. To reduce a matrix to a scalar value, use the all and any functions. continue The continue statement passes control to the next iteration of the for or while loop in which it appears, skipping any remaining statements in the body of the loop. In nested loops, continue passes control to the next iteration of the for or while loop enclosing it. break The break statement terminates the execution of a for loop or while loop. When a break statement is encountered, execution continues with the next statement outside of the loop. In nested loops, break exits from the innermost loop only 3. Error Control -- try, catch Error control statements provide a way for you to take certain actions in the event of an error. Use the try statement to test whether a certain command in your code generates an error. If an error does occur within the try block, MATLAB immediately jumps to the corresponding catch block. The catch part of the statement needs to respond in some way to the error. try and catch The general form of a try-catch statement sequence is try statement ... statement catch statement ... statement end In this sequence, the statements between try and catch are executed until an error occurs. The statements between catch and end are then executed. Use lasterr to see the cause of the error. If an error occurs between catch and end, MATLAB terminates execution unless another try-catch sequence has been established.
Sumit
514/EC/08
4. Program Termination -- return Program termination control enables you to exit from your program at some point prior to its normal termination point. return After a MATLAB function runs to completion, it terminates and returns control either to the function that called it, or to the keyboard. If you need to exit a function prior to the point of normal completion, you can force an early termination using the return function. return immediately terminates the current sequence of commands and exits the currently running function. return is also used to terminate keyboard mode.
General commands: Online help: help: lists topic on which help is available. demo: runs the demo programs. Workspace information: who lists variables currently in workspace. whos lists variables currently in workspace with their size. clear clear the workspace, variables are removed. clear all clears all variables and functions from workspace. clc clears command window, command history is lost. home same as clc. clf Command line help Help topics: Matlab/general: General purpose commands Matlab/ops: Operator and special characters Matlab/lang: Programming language constants Matlab/elmat: elementary matrix Matlab/elfun: elementary math function Matlab/specfun: specialized math function File types:1. M-files: script file and function file 2. Mat-files 3. Fig-files 4. P-files: are compiled m-files with P-extension 5. Mex-files: are for interface to higher languages M-files: Standard ASCII text files; m-extension Mat-files: Binary data files; mat-extension. These files are created by MATLAB. When you save data with save command. Sumit 514/EC/08
Fig files: Binary fig. files, fig-extension. They are saved as a figure through save option.
Program
% Program to display basic functions : 1.unit step , 2.unit impulse, 3.unit ramp functions.. clc; close all ; clear all; menu('functions','1.impulse','2.step','3.ramp'); n = input(' Enter the function number : '); switch n case 1 % impulse n1 =input ('Lower limit :'); Sumit 514/EC/08
n2 =input ('Upper limit :'); if n1 >= n2 error (' Invalid limits '); else a=[]; for i=n1:n2 if i==0 a= [a 1]; else a=[a 0]; end; end; stem(n1:n2 , a ); end; case 2 n1 =input ('Lower limit :'); n2 =input ('Upper limit :'); if n1 >= n2 error (' Invalid limits '); else a=[]; for i=n1:n2 if i>=0 a=[a 1]; else a=[a 0]; end; end; stem (n1:n2,a); end; case 3 n1 =input ('Lower limit :'); n2 =input ('Upper limit :'); if n1 >= n2 error (' Invalid limits '); else a=[]; for i=n1:n2 if i>=0 a=[a i] else a =[a 0]; end ; end; stem(n1:n2,a); end; end;
Output:
Enter the function number : 1 Lower limit :-3 Upper limit :4 Sumit 514/EC/08
>>
Enter the function number : 3 Lower limit :-2 Upper limit :4 >>
Program
% Program to represent basic signals: 1.Sin , 2.Cos , 3.Exponential. clc; close all; clear all; menu ('Functions','1.sine','2.cosine','3.exponential'); n =input ( 'Enter the function number :'); switch n case 1 % sin n1 =input (' Enter the lower limit :'); n2 =input ( 'Enter the upper limit :'); if n1>=n2 error ('Invalid limits '); else a=[]; for i=n1:.5:n2 a=[a sin(i)]; end ; stem(n1:.5:n2,a); title(' Sin function'); end ; case 2 %cosine n1 =input (' Enter the lower limit :'); n2 =input ( 'Enter the upper limit :'); if n1>=n2 error ('Invalid limits '); else a=[]; Sumit 514/EC/08
for i=n1:.5:n2 a=[a cos(i)]; end ; stem(n1:.5:n2,a); title(' Cosine function'); end ; case 3 % exponential n1 =input (' Enter the lower limit :'); n2 =input ( 'Enter the upper limit :'); if n1>=n2 error ('Invalid limits '); else a=[]; for i=n1:.5:n2 a=[a exp(i)]; end ; stem(n1:.5:n2,a); title('Exponential function'); end ; end;
Output:
Enter the function number :1 Enter the lower limit :-3 Enter the upper limit :4 >>
Sumit
514/EC/08
Enter the function number :2 Enter the lower limit :-3 Enter the upper limit :4 >>
Enter the function number :3 Enter the lower limit :-2 Enter the upper limit :8 >>
% Program for folding of a sequence clc; close all; clear all; n= input(' Enter the input sequence : '); a= input(' Enter the mask no.: '); nl=-(a-1);
Program
Sumit
514/EC/08
nr= length(n)-a ; subplot(1,2,1); stem(nl:nr,n); xlabel('No. of samples >>>> n : ') ; ylabel('Input sequence: x(n)'); title('Plot of sequence x(n)'); yl=-nr; yr=-nl; l=length(n); for j=1:length(n) m(j)=n(l); l=l-1; end; subplot(1,2,2); stem(yl:yr,m); xlabel('No. of samples >>> n: '); ylabel('Output sequence y(n) '); title('Plot of folded sequence ');
Output:
Enter the input sequence : [3 2 5 1 7 6 8] Enter the mask no.: 2 >>
P t o se u n x(n lo f q e ce ) 8 7 6 5 4 3 2 1 0 -2 Output sequence y(n) Input sequence: x(n) 8 7 6 5 4 3 2 1 0 -6 P t o fo e se u n lo f ld d q e ce
Program
% Program for convolution of sequences clc; close all; clear all; x=input('Enter the first sequence:'); h=input('Enter the second sequence:'); a=input(' Enter n=0 position for x from L.H.S.:'); b=input(' Enter n=0 position for h from L.H.S.');
Sumit
514/EC/08
xl=-(a-1); xr=length(x)-a; hl=-(b-1); hr=length(h)-b; yl=xl+hl; yr=xr+hr; y=conv(x,h); subplot(2,2,1); stem(xl:xr,x); xlabel('No. of samples > n'); ylabel('Amplitude entry > sequence x(n)'); title('Plot of sequence > x(n)'); subplot(2,2,2); stem(hl:hr,h); xlabel('No. of samples > n'); ylabel(' Amplitude entry > sequence h(n)'); title(' Plot of sequence h(n)'); subplot(2,2,3); stem(yl:yr,y); xlabel('No. of samples > n'); ylabel('Amplitude entry > sequence y(n)'); title('Plot of sequence > y(n)');
Output
Enter the first sequence:[2 4 9 2 7 4] Enter the second sequence:[2 1 9 4 9 2] Enter n=0 position for x from L.H.S.:2 Enter n=0 position for h from L.H.S.1 >>
Sumit
514/EC/08
0 -2
10
Program
%Program for discrete correlation of sequences clc; close all; clear all; x=input('Enter the first sequence:'); h=input('Enter the second sequence:');
Sumit
514/EC/08
a=input(' Enter n=0 position for x from L.H.S.:'); b=input(' Enter n=0 position for h from L.H.S.'); xl=-(a-1); xr=length(x)-a; hl=-(b-1); hr=length(h)-b; yl=xl+hl; yr=xr+hr; y=xcorr(x,h); subplot(2,2,1); stem(xl:xr,x); xlabel('No. of samples > n'); ylabel('Amplitude entry > sequence x(n)'); title('Plot of sequence > x(n)'); subplot(2,2,2); stem(hl:hr,h); xlabel('No. of samples > n'); ylabel(' Amplitude entry > sequence h(n)'); title(' Plot of sequence h(n)'); subplot(2,2,3); stem(yl:yr,y); xlabel('No. of samples > n'); ylabel('Amplitude entry > sequence y(n)'); title('Plot of sequence > y(n)');
Output
Enter the first sequence:[5 2 7 3 5 1] Enter the second sequence:[5 2 7 3 5 1] Enter n=0 position for x from L.H.S.:2 Enter n=0 position for h from L.H.S.1 >> Sumit 514/EC/08
150
100
50
0 -5
10
Program
%Program to understand sampling theorem clc close all clear all f1=1/128; n=0:255;
Sumit
514/EC/08
fc =50/128; x =cos(2*pi*f1*n) xa=cos(2*pi*fc*n) xamp= x.*xa; subplot(2,2,1); plot(n,x); title('x(n)') xlabel('n--->'); ylabel('amplitude'); subplot(2,2,2); plot(n,xa); title('xa(n)'); xlabel('n--->'); ylabel('amplitude'); subplot(2,2,3); plot(n,xamp); title('xa(n)'); xlabel('n--->'); ylabel('amplitude');
Output:
xn () 1 am plitude am plitude 0 .5 0 - .5 0 1 1 0 .5 0 - .5 0 1 x() an
10 0 n-> -x( ) an
20 0
30 0
10 0 n-> --
20 0
30 0
1 am plitude 0 .5 0 - .5 0 1
10 0 n-> --
20 0
30 0
Sumit
514/EC/08