Lab No.1
Lab No.1
Arshi Khalid
Date: 15-09-2022
Lab No. 01
Objective:
1) To learn the basics of Matlab.
Matlab:
MATLAB is a programming and numeric computing platform used by millions of
engineers and scientists to analyze data, develop algorithms, and create models.
Matlab Commands:
For Row Vector:
A = [1,2,3] or A = [1 2 3]
A = [1;2;3]
For Matrices:
A = [1,2,3;4,5,6;7,8,9]
Whos matrix_name
1
Lab report By: M.Hassan (2020-MC-274) Submitted To: Dr. Arshi Khalid
clear A
Eye (matrix_order)
For example, eye (4) will create a 4 x 4 identity matrix and eye (3,4) will create a 3 x 4 identity matrix.
clc
clearvars
sin(angle)
The default angle is always in Radian in Matlab. We could replace sin with cos & tan for their values.
sind(angle)
sqrt(variable)
help command_name
ones (order_of_matrix)
for example: ones (3,4) will generate a matrix of order 3 x 4 having 1’s.
zeros (order_of_matrix)
for example: zeros (3,4) will generate a matrix of order 3 x 4 having 0’s.
2
Lab report By: M.Hassan (2020-MC-274) Submitted To: Dr. Arshi Khalid
for example: b (3,4) = 4 will replace the 3rd row and 4th column entry with 4.
To generate a string:
‘Characters_of_the_strings_to_be_generated’
B = rand (order_of_the_random_matrix)
OR B = magic (order_of_the_matrix)
Size (name_of_the_matrix)
for example: size (b) will tell us the order of the matrix b.
length (name_of_the_matrix)
for example: length (b) will tell us the number of columns of matrix b.
for example: if a is a 3 x 4 matrix then a (:,4) = [ ] will remove the 4th column of the matrix and display
the remaining matrix.
for example: if a is a 3 x 4 matrix then a (3,:) = [ ] will remove the 3rd row of the matrix and display the
remaining matrix.
for example: x = linspace (-10, 10, 100) will generate a linearly spaced vector from -10 to 10 having 100
entities.
Note:
o If we want to declare/calculate something in main program and don’t want to show that value in
command window, then we will put semicolon (;) sign at the end of that line.
o The name of the main program should not start from a number (like1,2 etc.). And there should’nt be
any space in the name of the main program.
Lab task_1 (solve for a function of cube root of unity with fsolve):
Matlab Program:
1. clc;
2. clearvars;
3. % solve for a function of cube root of unity with fsolve
4. % 1^1/3 = x --> x^3 = 1 --> x^3 - 1 = 0
5. f = @(x) [x^3 - 1];
6. % solve function for x=1
7. f([1]);
8. % Now solve using fsolve
9. fsolve (f, [1])
10. % find the value of x and function(fval)
11. [x, fval] = fsolve (f, [1])
Output:
x = 1
fval = 0
Lab task_2 (Convert a matrix into diagnol matrix without using diag command):
Matlab Program:
1. clc;
2. clearvars;
3. close all;
4. x = [1,1,1,1;2,2,2,2;3,3,3,3;4,4,4,4]
5. for m = 1:length(x)
6. for n = 1:length(x)
7. if n==m
8. x(n,m)= 1
9. else
10. x(n,m)= 0
11. end
12. end
13. end
Output:
x =
1 0 0 0
0 1 0 0
4
Lab report By: M.Hassan (2020-MC-274) Submitted To: Dr. Arshi Khalid
0 0 1 0
0 0 0 1