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

Lab # 1

The document provides an overview of basic MATLAB commands and functions for matrix arithmetic, plotting graphs, and 3D visualization. It demonstrates how to create and manipulate matrices, plot 2D and 3D graphs, add labels and legends, create subplots, and visualize 3D surfaces.

Uploaded by

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

Lab # 1

The document provides an overview of basic MATLAB commands and functions for matrix arithmetic, plotting graphs, and 3D visualization. It demonstrates how to create and manipulate matrices, plot 2D and 3D graphs, add labels and legends, create subplots, and visualize 3D surfaces.

Uploaded by

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

Lab # 01

Object: To Display the basics commands, matrix arithmetic, and graph plotting in MATLAB.

Theory:
MATLAB is short for Matrix Laboratory, and is designed to be a tool for quick and easy
manipulation of matrix forms of data. The basic data element in MATLAB is a matrix. A scalar
in MATLAB is a 1x1 matrix, and a vector is a 1xn (or nx1) matrix.

There are a few basic MATLAB features that are helpful to know.
 A semicolon (;) at the end of a command line tells MATLAB to execute the command but
not display the answer.
 Variable names must be one word (underscores are acceptable), and some names initially
mean something to MATLAB until their definition is overridden, e.g., pi equals π.
 Text after a percent sign (%) is interpreted as a comment.
Procedure:
When you start MATLAB, the command prompt “˃˃” appears. Now, here you will tell
MATLAB what to do by typing commands at the prompt.
Lab Practice:
1. Create a 3x3 matrix A that has 1’s in the first row, 2’s in the second row, and 3’s in the
third row:
A = [1 1 1; 2 2 2; 3 3 3]
The semicolon is used here to separate rows in the matrix
A=
1 1 1
2 2 2
3 3 3

2. If you don’t want MATLAB to display the result of a command, put a semicolon at the
end:
A = [1 1 1; 2 2 2; 3 3 3];

Matrix A has been created but MATLAB doesn’t display it. The semicolon is necessary when
you’re running long scripts and don’t want everything written out to the screen

3. Suppose you want to access a particular element of matrix A:


A(1,2)
ans =

3
1
4. Suppose you want to access a particular row of A:
A(2,:)
ans =
2 2 2

The “:” operator you have just used generates equally spaced vectors. You can use it to specify
a range of values to access in the matrix:
A(2,1:2)
ans =
2 2
You can also use it to create a vector:
y = 1:3
y=
1 2 3

The default increment is 1, but you can specify the increment to be something else:
y = 1:2:6
y=

1 3 5
The value of each vector element has been increased by 2, starting from 1, while less than 6.
5. You can also easily delete matrix elements. Suppose you want to delete the 2nd element
of the vector y:
y(2) = []
y=
1 5

6. MATLAB has several built-in matrices that can be useful. For example, zeros(n,n) makes
an nxn matrix of zeros.
B = zeros(2,2)

B=
0 0
0 0

4
A few other useful matrices are:
o zeros – create a matrix of zeros
o ones – create a matrix of ones
o rand – create a matrix of random numbers
o eye – create an identity matrix
7. Add two matrices together is just the addition of each of their respective elements. If A
and B are both matrices of the same dimensions (size), then
A = [1 3 5 ; 7 9 11]
B = [2 4 6 ; 8 10 12]
C=A+B
C
3 7 11
15 19 23
An important thing to remember is that since MATLAB is matrix-based, the multiplication
operator “*” denotes matrix multiplication. Therefore, A*B is not the same as multiplying each
of the elements of A times the elements of B. However, at some point you want to do element-
wise operations (array operations). In MATLAB you denote an array operator by playing a
period in front of the operator. The difference between “*” and “.*” is demonstrated in this
example
A = [1 1 1; 2 2 2; 3 3 3];
B = ones(3,3);
A*B
ans =
3 3 3
6 6 6
9 9 9

A.*B
ans =
1 1 1
2 2 2
3 3 3
Other than the bit about matrix vs. array multiplication, the basic arithmetic operators in
MATLAB work pretty much as you’d expect. You can add (+), subtract (-), multiply (*), divide
(/), and raise to some power (^).

MATLAB provides many useful functions for working with matrices. It also has many scalar
functions that will work element-wise on matrices. Below is a brief list of useful functions.
o A´ – transpose of matrix A. Also transpose(A).
o det(A) – determinant of A

5
o eig(A) – eigenvalues and eigenvectors
o inv(A) – inverse of A
o svd(A) – singular value decomposition
o norm(A) – matrix or vector norm
o find(A) – find indices of elements that are nonzero. Can also pass an expression
to this function, e.g. find(A > 1) finds the indices of elements of A greater than
1.
A few useful math functions:
o sqrt(x) – square root
o sin(x) – sine function. See also cos(x), tan(x), etc.
o exp(x) – exponential
o log(x) – natural log
o log10(x) – common log
o abs(x) – absolute value
o mod(x) – modulus
o factorial(x) – factorial function
o floor(x) – round down. See also ceil(x), round(x).
o min(x) – minimum elements of an array. See also max(x).
o besselj(x) – Bessel functions of first kind

6
Graph Plotting
Theory:
1. 2D PLOTTING
The most basic 2D symbol and line plot command is
plot (x,y)
Where x and y are vectors of the same type (row or column) and length that contain the data to
be plotted.
Lab Practice:

1. Create a plot of the sine function sind where the d requires that the argument be in degrees.
Do this by first creating a row vector x consisting of 37 values

x = [0:10:360];

Next, evaluate the sind function at each of these values and store those values in a row vector
y1
y1 = sind(x);
Now create the plot
plot(x,y1);
Which will appear in the figure window.

2. To use the ‘plot’ function in Matlab, you should first make sure that the matrices/vectors you
are trying to use are of equal dimensions. For example, if I wanted to plot vector X = [3 9 27]
over time, my vector for time would also need to be a 1x3 vector (i.e. t = [1 2 3]).
X = [3 9 27]; % my dependent vector of interest
t = [1 2 3]; % my independent vector
figure % create new figure
plot(t, X)
2. Labeling Axes: To give the above figure a title and axis labels:
title(‘Plot of Distance over Time’) % title
ylabel(‘Distance (m)’) % label for y axis
xlabel(‘Time (s)’) % label for x axis

7
o Legends: If you have plotted multiple dependent vectors on the same plot and want to
distinguish them from each other via a legend, the syntax is very similar to the axis
labeling above. It is also possible to set colors for the different vectors and to change the
location of the legend on the figure.
X = [3 9 27]; % dependent vectors of interest
Y = [10 8 6];
Z = [4 4 4];
t = [1 2 3]; % independent vector
figure
hold on % allow all vectors to be plotted in same figure
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

8
o 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:
% subplot (nrows,ncols,plot_number)
x=0:.1:2*pi; % x vector from 0 to 2*pi, dx = 0.1
subplot(2,2,1); % 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);

9
2. 3-D Plotting
There are also ways to plot in multiple dimensions in Matlab. One type of 3-D plot that may
be useful is a surface plot, which requires you to generate some kind of x-y plane and then
apply a 3rd function as the z dimension.
Lab Practice:

1. MATLAB has several plotting commands to visualize data in 3D. For example, let

[x,y] = meshgrid([-2:.2:2]); % set up 2-D plane


Z = x.*exp(-x.^2-y.^2); % plot 3rd dimension on plane figure
surf(x,y,Z,gradient(Z)) % surface plot, with gradient(Z)
% determining color distribution
colorbar % display color scale, can adjust
% location similarly to legend

10
2. Consider the function z (x, y) of two variables x and y such that

The first step in visualizing this function in 3D is to create a grid in the xy plane which can be
accomplished with the meshgrid command. The following command will create an equally
spaced grid (0.15 spacing in each direction) over -2.1 ≤ x ≤ 2.1 and -6 ≤ y ≤ 6

[x, y] = meshgrid(-2.1:0.15:2.1, -6:0.15:6);

The function now is evaluated at each of the grid points with the command

z = 80*y.^2.*exp(-x.^2-0.3*y.^2);

Note the periods after the vectors x and y containing the spatial coordinates; these ensure that
the subsequent operation is performed on each element of the vector and not attempted on the
vector itself.

To create a wire frame mesh of the function, enter this command


mesh(z);

11
The function surf should generate the surface plot
surf(z);

12

You might also like