Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
19 views10 pages

Experiment 1 (Matlab Prog.)

The document provides an introduction to MATLAB programming, covering essential concepts such as the Command, Figure, and Editor windows, as well as arithmetic operations, complex numbers, array indexing, and memory allocation. It also details special functions, plotting techniques, user input, display commands, and control structures like if statements and loops. The content is aimed at students in the Signals and Systems LAB course, offering practical examples and tasks to enhance understanding of MATLAB.

Uploaded by

dhwalfqarhsyn32
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views10 pages

Experiment 1 (Matlab Prog.)

The document provides an introduction to MATLAB programming, covering essential concepts such as the Command, Figure, and Editor windows, as well as arithmetic operations, complex numbers, array indexing, and memory allocation. It also details special functions, plotting techniques, user input, display commands, and control structures like if statements and loops. The content is aimed at students in the Signals and Systems LAB course, offering practical examples and tasks to enhance understanding of MATLAB.

Uploaded by

dhwalfqarhsyn32
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Signals and Systems LAB (SGSY257) 2nd year,2nd semester

Introduction to MATLAB Prepared by Dr. Yasmine M. Tabra


Dr. Mohammed H. Ali

Experiment No. 1
MATLAB Programming
1. General View
MATLAB (Matrix Laboratory) is a high-level programming language that has been
used extensively to solve engineering and science problems in academic and research
institutions as well as industry.
MATLAB works with three types of windows on your computer screen. These are:

A. The Command window: The command window is the main window in which you
communicate with the MATLAB interpreter. The MATLAB interpreter displays a command
prompt >> indicating that it is ready to accept commands from you. You can use command
window to enter variables and run functions and M-files and controlling input and output data.
You can clear the Command window with the clc.
Say you want to evaluate the expression f where a=1.2, b=2.3, c=4.5 and d=4. Then in the
command window, type:
a =1.2;
b =2.3;
c =4.5;
d =4;
f=a^3+sqrt(b*d)-4*c
ans = -13.2388

B. The Figure window: The Figure window only pops up whenever you plot something.

Figure; plot(a,b,‘x’);
1
Signals and Systems LAB (SGSY257) 2nd year,2nd semester
Introduction to MATLAB Prepared by Dr. Yasmine M. Tabra
Dr. Mohammed H. Ali

% Define data points


a =0:5; % X-coordinates
b =1:6; % Y-coordinates
Plot (a,b,'-x')

C. The Editor window: The Editor window is used for writing and editing MATLAB programs
(called M-files) and can be invoked in Windows from the pull-down menu after selecting File |
New | M-file.

Note: the semicolon after each variable assignment. If you omit the semicolon, then MATLAB
echoes back on the screen the variable value.

2. Arithmetic Operations
There are four different arithmetic operators:
+ Addition
− Subtraction
* Multiplication
/ Division (for matrices it also means inversion)

X =[1,3,4]
Y =[4,5,6]
X+Y
ans = 5 8 10
For the vectors X and Y, the operator ‘+’ adds the elements of the vectors, one by one, assuming that
the two vectors have the same dimension.
To compute the dot product of two vectors, you can use the multiplication operator *. For the above
example, it is:
X*Y’
ans = 43
This means (1×4 + 3×5 + 4×6 = 43 ). Note the single quote (’) after Y. The single quote denotes the
transpose of a matrix or a vector.

In MATLAB, most arithmetic operations (+, -, *, /, ^) are designed for matrix operations. However,
when performing element-wise operations, MATLAB provides special operators that work on
corresponding elements of arrays or matrices.
Three Important Element-wise Operators:
1- Element-wise Multiplication (.*). %Multiplies corresponding elements of two arrays.
A = [1 2 3];
B = [4 5 6];
C = A .* B; % Result: [4 10 18].
The ‘.*’ operator in MATLAB is highly recommended because it is significantly faster than using for
loops for element-wise computations.

2
Signals and Systems LAB (SGSY257) 2nd year,2nd semester
Introduction to MATLAB Prepared by Dr. Yasmine M. Tabra
Dr. Mohammed H. Ali

2- Element-wise Division (./). %Divides each element of one array by the corresponding element of another.
A = [10 20 30];
B = [2 4 5];
C = A ./ B; % Result: [5 5 6].
3- Element-wise Exponentiation (.^).% Raises each element of an array to the power of the
corresponding element in another array.

3. Complex Numbers

MATLAB supports complex numbers, and the imaginary unit is represented by i or j, provided
that you have not redefined them as variables in your code.
Try the following:
z=3 + 4i
conj(z) % computes the conjugate of z
angle(z) % computes the phase of z
real(z) % computes the real part of z
imag(z) % computes the imaginary part of z
abs(z) % computes the magnitude of z

z1 = 3 + 4i;
z2 = 1 - 2i;
sum_z = z1 + z2; % Addition
prod_z = z1 * z2; % Multiplication
div_z = z1 / z2; % Division
conj_z = conj(z1); % Complex conjugate
abs_z = abs(z1); % Magnitude (modulus)
angle_z = angle(z1); % Phase angle in radians

Note: In MATLAB, you can define the imaginary unit using any variable name, as long as you
explicitly assign it a complex value. Here’s an example:

im = 1i; % Define 'im' as the imaginary unit


z1 = 3 + 4*im; % Define a complex number
z2 = 2 - 5*im; % Another complex number

% Perform operations
sum_z = z1 + z2; % Addition
prod_z = z1 * z2; % Multiplication
abs_z1 = abs(z1); % Magnitude of z1

3
Signals and Systems LAB (SGSY257) 2nd year,2nd semester
Introduction to MATLAB Prepared by Dr. Yasmine M. Tabra
Dr. Mohammed H. Ali

D. Array Indexing
In MATLAB, arrays (or vectors) use 1-based indexing, meaning the first element is accessed with
index 1, i.e., y(1), not 0 as in C/C++. Also, MATLAB uses parentheses () for indexing instead of
square brackets [] like in C/C++.
To create an array having as elements the integers 1 through 6, just enter:
Method 1: Using Colon Operator (:)
x= 1:6;

The ‘:’ notation above creates a vector starting from 1 to 6, in steps of 1. If you want to create a
vector from 1 to 6 in steps of, say 2, then type:
x=1:2:6
ans = 1 3 5

Method 2: Using linspace


y = linspace(1, 6, 6);

Method 3: Using [] (Explicit Definition)


y = [1 2 3 4 5 6];
This manually defines the vector.
Accessing Elements in the Array
• First element: y(1); Last element: y(end); Third element: y(3)

y(2) = 10; % Changes the second element to 10

In MATLAB, extracting, inserting, and concatenating elements in a vector can be done easily
using parentheses () for indexing and square brackets [] for concatenation.
A = [1 2 3]; % First array
B = [4 5 6]; % Second array

C = [A B]; % Concatenate horizontally


D = [A; B]; % Concatenate vertically

To access a subset of the array, try the following:


y(3:6)
length(y) % gives the size of the array or vector
y(2:2:length(y))

Inserting Elements into a Vector


Insert an Element (3) at a Specific Position

y = [1 2 4 5];
y = [y(1:2) 3 y(3:end)]; % Insert 3 between 2 and 4

4
Signals and Systems LAB (SGSY257) 2nd year,2nd semester
Introduction to MATLAB Prepared by Dr. Yasmine M. Tabra
Dr. Mohammed H. Ali

E. Allocating Memory
In MATLAB, you can preallocate memory for a one-dimensional array (vector) using the zeros
command. This is useful for efficiency, especially when dealing with large arrays.
Example: Allocating Memory for a 100-Dimensional Array
y = zeros (100, 1); % Creates a 100×1 column vector filled with zeros
y = ones (1, 100); % 1×100 vector filled with ones

y = rand(1, 100); % 1×100 vector with random values between 0 and 1

Similarly, you can allocate memory for two-dimensional arrays (matrices). The command
y=zeros(4,5) % defines a 4 * 5 matrix. Similar to the zeros command,

F. Special Characters and Functions


Some common special characters used in MATLAB are given below:

special function is given below:

find - Finds indices of nonzero elements.


The function ‘find’ returns the indices of the vector X that are non-zero or matrix that meet a
specified condition.
returns a vector containing the linear indices of each nonzero element in array X.
For example, I = find(X> 4), finds all the indices of X when X is greater than 4.
X = [1 5 3 7 4 9];
I = find (X > 4)
I=
2 4 6
Example: Find the nonzero elements in a 3-by-3 matrix.
x = [1 0 2; 0 1 1; 0 0 4]
5
Signals and Systems LAB (SGSY257) 2nd year,2nd semester
Introduction to MATLAB Prepared by Dr. Yasmine M. Tabra
Dr. Mohammed H. Ali

K=find(x)
k=

1
5
7
8
9
Use the logical not operator on x to locate the zeros.
S = find(~x)

Example: Find the elements that are less than 10 in a 4-by-4 magic square matrix.
A = magic(4)
k = find(A<10)

G. Plotting
You can plot arrays using MATLAB’s function plot. The function plot(.) is used to generate line
plots. The function stem(.) is used to generate “picket-fence” type of plots.
x=1:20;
plot(x)
stem(x)

More generally, plot(x,y) plots vector y versus vector x. Various line types, plot symbols and colors
may be obtained using plot(x,y,s) where s is a character string indicating the color of the line, and the
type of line (e.g., dashed, solid, dotted, etc.).
plot(x,y,'--r')
x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y,’*g’)
You can insert x-labels, y-labels, and title to the plots, using the functions, xlabel(.), ylabel(.) and
title(.) respectively.
figure; % figure creates a new figure window using default property values
title('Lab exp 1'); %Put a title for the plot
xlabel('trial'); ylabel('distance, ft');%Name for x-axis and y-axis
xlim([-1 10]); ylim([0 6]); %Define the limits for each axis
axis([-1 10 0 6]); %Define the limits for both axis
grid on; %Producing lines for scale divisions(grids)
figure(1); % Opens or activates Figure 1
Create Multiple Figures
plot(1:10, (1:10).^2, 'r'); % Plot in Figure 1
grid on;
figure(2); % Opens or activates Figure 2
plot(1:10, sqrt(1:10), 'b'); % Plot in Figure 2
grid on;
6
Signals and Systems LAB (SGSY257) 2nd year,2nd semester
Introduction to MATLAB Prepared by Dr. Yasmine M. Tabra
Dr. Mohammed H. Ali

To plot two or more graphs on the same figure, use the command subplot. For instance, to show the
above two plots in the same figure, type:

x=1:8;
subplot(2,1,1), plot(x)
subplot(2,1,2), stem(x)

The (m,n,p) argument in the subplot command indicates that the figure will be split in m rows and n
columns. The ‘p’ argument takes the values 1, 2 . . . m×n. In the example above, m = 2, n = 1,and p
= 1 for the top figure and p = 2 for the bottom figure.
**** To get more help on plotting, type: help plot or help subplot.

H. Input command
In MATLAB, users can enter data through the keyboard using the input function. This is useful for
interactive scripts where user input is needed.
e.g: z = input('Enter values for z in brackets=');
When executed, the screen displays
Enter values for z in brackets =

Then the user can enter, say, [5.1 6.3 -18] {here we assign row vector with 3 elements to z}
• Since the command does not end with a semicolon (;), MATLAB displays the assigned
values in the Command Window.
• If you add a semicolon, the values will be stored in z but not displayed

I. Display command
In MATLAB, the disp function is used to display values or messages in the Command Window
without printing variable names or extra formatting.
temp = 78;
disp(temp); % Displays the value of temp
disp('Degrees F'); % Displays the text

Combining Text and Numbers Using disp


disp(['Temperature = ' num2str(temp) ' Degrees F'])
For more control over formatting, use fprintf.
fprintf('Temperature = %.1f Degrees F\n', temp);

7
Signals and Systems LAB (SGSY257) 2nd year,2nd semester
Introduction to MATLAB Prepared by Dr. Yasmine M. Tabra
Dr. Mohammed H. Ali

J. Control & Loop statements


1. if statement

In MATLAB, the if-elseif-else structure is used to execute statements based on


conditions.
Execute statements if condition is true.
if condition1
statement1;% Executes statement1 if condition1 is
true.
elseif condition2
statement2; % Checks condition2 if condition1 is
false.
else
statement3; %Executes statement3 if none of the
conditions are met.
end
Example
% Generate a random number
a = randi(100, 1);
% If it is even, divide by 2
if rem(a, 2) == 0
disp('a is even')
else
disp('a is odd')
end

2. switch & case statement


switch (expression)
case 0
statement 1; case 1
statement 2; case 2
statement 3;
otherwise
error( ’error statement'); % Executes if no case matches (optional but recommended).
end % Ends the switch block.
Example
n = input('Enter a number: ');
switch n
case -1
disp('negative one')
case 0
disp('zero')
case 1
disp('positive one')
otherwise
disp('other value')
end

8
Signals and Systems LAB (SGSY257) 2nd year,2nd semester
Introduction to MATLAB Prepared by Dr. Yasmine M. Tabra
Dr. Mohammed H. Ali

Task: Write a MATLAB script that asks the user to enter a day of the week and then
prints a corresponding message using a switch-case statement.

3. Loop Control – for


The for loop is used to repeat a set of statements for a fixed number of times. It is
commonly used for iterating over arrays, performing computations, and
automating repetitive tasks.
for i=1: n
statement(s);
end
Example use if and for ? At the end print the values of c & check
c = zeros(1,10); % Preallocate for efficiency
for a=1:10;
if a<3
c(a)=a^2;
elseif a<7
c(a)=a+5;
else
c(a)=a;
end
end
output: c = [1, 4, 8, 9, 10, 11, 7, 8, 9, 10]

4. Loop Control – while


The while loop in MATLAB is used when you do not know in advance how many
times the loop will run. It continues to execute as long as the condition is true.
while(condition =True)
statements;

Example
% find factorial of 4
n = 4; % Initialize n as 4
f = n; % Start f with the value of n (4)
while n > 1 % Continue looping while n is greater than 1
n = n-1; % Decrease n by 1 in each iteration
f = f*n; % Multiply f by the new value of n
end
disp(['n! = ' num2str(f)]) % display numbers as strings

9
Signals and Systems LAB (SGSY257) 2nd year,2nd semester
Introduction to MATLAB Prepared by Dr. Yasmine M. Tabra
Dr. Mohammed H. Ali

step-by-Step Execution
Iteration n Before Update n After Update (n= n - 1) f (Updated as f * n)
1st 4 3 4 * 3 = 12
2nd 3 2 12 * 2 = 24
3rd 2 1 24 * 1 = 24
4th 1 (Loop stops) (Final result)

10

You might also like