Lab_1
Lab_1
INTRODUCTION TO MATALAB
Signature:______________ Date:
OBJECTIVES:
The purpose of this lab is to familiarize with basic MATLAB functionality. You will also be able
to learn how vectors are defined and represented in MATLAB.
MATLAB is a high-level computer language used for the programming of complex engineering
problems. MATLAB stands for Matrix Laboratory. As the name suggests, MATLAB a plethora
of functions used for different operations on matrices, where a matrix can be scalar (single
element), a vector (one dimensional) or an n x m Matrix (two dimensional). The MATLAB
desktop is the main MATLAB application window. In Figure 1, the desktop contains five sub-
windows: The Command Window, the Workspace Browser, the Current Directory Window, the
Command History Window, and one or more Figure Windows, which are shown only when the
user displays a graphic.
The Command Window is where the user type MATLABN commands and expressions at the
prompt (>>) and where the outputs of those commands are displayed. MATLAB defines the
workspace as the set of variables that the user creates in work session. The Workspace Browser
shows those variables and some information about them.
The Current Directory tab above the Workspace tab shows the contents of the current directory,
whose path is shown in the Current Directory Window. Clicking on the button to the right of the
window allows the user to change the current directory. MATLAB uses a search path to find M-
files and other MATLAB. Any file run in MATLAB must reside in the current directory or in the
directory that is on the search path. The easiest way to see which directories are on the search
path, or to add or modify a search path is to select Set Path from the File menu on the desktop,
and then use the Set Path dialog box.
The Command History Window contains a record of the commands a user has entered in the
Command Window, including both current and previous MATLAB sessions. Previously entered
MATLAB commands can be selected and re-executed from the Command History Window by
right-clicking on a command. This action launches a menu from which to select various options
in addition to executing the commands. This is a useful feature when experimenting with various
commands in a work session.
Getting Started:
To run MATLAB simply double-click the MATLAB icon on the desktop or find the MATLAB
command in the start menu. This will open a MATLAB command window, which displays a
prompt “>>”. The commands are typed at this prompt. The “>>” is the MATLAB prompt. There
is no need to type that part. Explore the built-in demos by typing demo.
MATLAB BASICS:
• Getting Help:
MATLAB provides an online help system accessible by using the help command. For
example, to get information about the function size, enter the following:
>> help size
There also is a help desk (formatted in HTML for viewing from a Web browser) with useful
introductory material. It is accessed from the Help menu. If you have no prior experience
with MATLAB, see the topic “Getting Started” in the help desk. Spend some time with this.
You can find in the help desk all the information you need to carry out the exercises.
• Variables:
MATLAB does not require the variables to be declared before their use. To assign value to a
variable equal “=” sign is used. To set x equal to 2 write at command prompt.
>> x = 2
Ans =
16
Ans is also MATLAB variable.
• Suppressing output:
When we type a command, function or variable name, its value appears on the screen.
Sometimes it is inconvenient if you do not want to display the output at every step of your
program. The output display of the value can be suppressed by putting the semicolon at the
end of command or variable name. If the semicolon is not present at the end of a command
line, MATLAB outputs the contents of the operation on the screen.
>> clc
Clears the variable from the workspace. This is useful when we want to reclaim system
memory.
The simplest way to create a row vector is by using concatenation brackets or square
brackets. Various values in a row vector can be separated by space or comma. In column
vector various values are separated by semicolon.
>> x = [1 2 3 4]
>> y = [1; 2; 3; 4]
This will create a row vector x and column vector y. To convert a row vector into column
vector and vice versa transpose operator .’ is used.
>> x1 = x.’
>> y1 = y.’
An array has dimensions M × N, where M and N are positive integers. M is the number of
rows and N is the number of columns.
If M= N = 1, the variable is a scalar.
If M = 1and N > 1, then the variable is a row vector.
If M > 1 and N = 1, then the variable is a column vector.
If both M and N are greater than one, then the variable is a matrix.
If M = N, then the variable is a square matrix.
The coefficients of an array are real or complex numbers.
• Strings:
Characters enclosed in single quotes are defined as strings. In the simplest case strings are
used for displaying messages.
• Comments
Starting a line with percent % sign tells MATLAB that line is a comment. As with other
programming languages it is very important to comment your code. If comments are placed
in very beginning of m-file, then by typing help filename, MATLAB prints the comments
that appear at the beginning of file. This will allow the user to expand MATLAB help
facility.
A variable can be displayed by entering the variable name without semicolon. A more
flexible way of displaying the variable is by using disp(var) command where variable stands
for arbitrary variable name.
Finally, combined messages can be created by converting numerical variables into strings
and concatenating them with the string variable containing the message.
x = sqrt(25);
message = ‘The value of x is : ‘;
d = [message num2str(x)];
disp(d)
>> A = [1 2 3; 4 5 6; 7 8 9]
creates a 3 x 3 matrix in MATLAB in which the first the workspace row has elements 1, 2, 3, the
second row has elements 4, 5, 6, and so on (note the use of the brackets [ ]). If, instead, we write
the same line without the final semicolon, we would get
>> A = [1 2 3; 4 5 6; 7 8 9]
One of MATLAB most powerful index operators is the colon operator ”:”. It is used in several
different forms. For example, writing
>> 1:5
produces the row of integers 1 2 3 4 5
If we wanted to create a 1 x N matrix, X, containing the sequence 1, 2 . . . N for an integer value
of N, we would write.
>> X = 1:N;
Alternatively, we could use the fact that a:b is the same as colon(a,b) and write.
100 90 80 70 60 50
>> C3 = A (:,3)
C3 =
3
6
9
>> R2 = A (2,:)
R2 =
456
>> T2 = A (1:2,1:3)
T2 =
123
456
GENERATING MATRICES:
MATLAB provides four functions that generate the following basic matrices:
-- zeros(M,N) generates an M x N matrix of zeros.
-- ones(M,N) generates a M x N matrix of ones.
-- rand(M,N) generates a M x N matrix whose entries are uniformly distributed
random numbers in the interval [0:0; 1:0].
-- randn(M,N) generates a M x N matrix whose numbers are normally distributed (i.e., Gaussian)
numbers with mean 0 and variance 1.
For example:
B=
0.2311 0.4860 0.7621 0.0185
0.6068 0.8913 0.4565 0.8214
MATRIX CONCATENATION:
Matrix concatenation is the process of joining small matrices to create larger matrices. The
concatenation operator is the pair of square brackets, [ ]. Earlier in this section when we wrote.
>> A = [1 2 3; 4 5 6; 7 8 9]
All we did was concatenate three rows (separated by semicolons) to create a 3£3 matrix. Note
that individual elements are separated by a space. Separating the elements by commas would
yield the same result. Also note the order in which the elements were concatenated. The group of
three elements before the first semicolon formed the first row, the next group formed the second
row, and so on. Clearly the number of elements between semicolons must be equal. This concept
is applicable also when the elements themselves are matrices. For example, consider the 2 x 2
matrix.
The statement
in which B + 4 and B - 1 indicate adding 4 and subtracting 1 from all elements of B, respectively,
yields the result.
C=
1212
3434
5601
7823
Note how matrix B was duplicated twice in the top half of C, corresponding to the two
occurrences of B before the first semicolon in the statement C = [B B;B+4 B-1].
TRIGONOMETRIC FUNCTIONS:
1.5000
>> y=4*sin (pi/6)
y=
2.0000
>> x=3*cosd (pi/3)
x=
2.9995
>> y=4*sind (pi/6)
y=
0.0366
‘d’ denotes the degree ,if we use ‘d’ the result of trigonometric function will be in degrees.
SCALAR PRODUCT:
The scalar produce is defined by multiplying the corresponding elements together and
adding the results to give a single number. Suppose we have the following vectors:
u= [8 -11 10]
v= [10 ; -21 ; -52]
w= [2 1 3]
The command for scalar produce is "*". However, the vector (or matrix) dimensions must
agree, i.e. 1xn vector can be multiplied with nx1 vector.
>> u*v
ans =
-209
>> u*w
??? Error using ==> mtimes
Inner matrix dimensions must agree.
>> u*w'
ans =
35
>> u*u'
ans =
285
SIZE OF A MATRIX:
PRACTICE QUESTIONS
Q1. What is the difference between u*w and u.*w commands. ? Take any 3x3 matrices of u
and w. write Matlab code and show the results as well.
Code:
U = [1 2 3; 4 5 6; 7 8 9];
W = [9 8 7; 6 5 4; 3 2 1];
Matrix_multiplication = u * w;
Elementwise_multiplication = u .* w;
Disp(“Matrix multiplication:”);
Disp(matrix_multiplication);
Disp(“Element-wise multiplication:”);
Disp(elementwise_multiplication);
Output:
>> u1
Matrix multiplication:
30 24 18
84 69 54
138 114 90
Element-wise multiplication:
9 16 21
24 25 24
21 16 9
Q2. Write the outputs of the commands for the following matrix
A=[ 1 2 5; 8 6 1; 5 2 9]
• A(:,:)
• A(:,1)
• A(2,:)
• A(2:3,2:3)
• A(:,2)
A(:,:)
Output:
Copy code
125861529
matlabCopy code
Output:
Copy code
185
matlabCopy code
Output:
Copy code
861
matlabCopy code
Output:
Copy code
6129
matlabCopy code
Output:
Copy code
262
Q3. Write the MATLAB code to find the roots of the quadric equation 3x2+4x-2 using the
MATLAB built in command and also by using quadratic equation. Write MATLAB code
and results as well.
3x2+4x-2
A = 3;
B = 4;
C = -2;
Disp(roots_builtin);
Disp(“Roots using quadratic formula:”);
Disp(root1);
Disp(root2);
OUTput:
-1.4363
0.4363
-1.4363
Q4. Write MATLAB code to generate the sequence 20 40 60 80 100 120 140.
CODE:
Sequence = [];
initialValue = 20;
commonDifference = 20;
for I = 1:7
term = initialValue + (i-1) * commonDifference;
sequence = [sequence, term];
end
disp(sequence);
output: