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

Programming in Matlab 21BRL57

The document is a laboratory manual for a MATLAB programming course at Mysore University School of Engineering, detailing various experiments and exercises. It covers fundamental concepts of MATLAB, including input/output operations, vector and matrix operations, and functions for solving quadratic equations. The manual is prepared by Mr. Thanmay J S and includes practice programs for students to enhance their understanding of MATLAB.

Uploaded by

Thanmay JS
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)
7 views

Programming in Matlab 21BRL57

The document is a laboratory manual for a MATLAB programming course at Mysore University School of Engineering, detailing various experiments and exercises. It covers fundamental concepts of MATLAB, including input/output operations, vector and matrix operations, and functions for solving quadratic equations. The manual is prepared by Mr. Thanmay J S and includes practice programs for students to enhance their understanding of MATLAB.

Uploaded by

Thanmay JS
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/ 36

Mysore University School of Engineering

8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006

Programming in MATLAB
(21BRL57)

Laboratory Manual with Experiments

Name of the Student:

Register Number:

Branch:

Semester:

Prepared by: Mr Thanmay J S, Assistant Professor, Bio-Medical & Robotics Engineering, UoM, SoE, Mysore 57006
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006

Course Content
Introduction to Matlab

1. Program to understand different modes of input/output operations on numerical data and character strings

2. Programs to define and perform different operations on vector.

3. Programs to understand the basic operations on matrix.

4. Program to find the roots of a quadratic equation

5. Program to understand different arithmetic operators

6. Program to understand different logical operations

7. Program to understand different set operators

8. Program to define a user-defined function and call this function in the main program to realize the task.

9. Programs to understand basic algebra functions.

10. Programs to create and manipulate cell arrays.

11. Program to generate and plot and subplot 2D and 3D data

12. Program to understand the control structures: if, if-else and switch

13. Program to understand the loop structures: while and for

14. Program to find the roots of a given polynomial and to construct the polynomial from the given roots of

the polynomial.

Prepared by: Mr Thanmay J S, Assistant Professor, Bio-Medical & Robotics Engineering, UoM, SoE, Mysore 57006
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Introduction to Matlab
MATLAB (short for MATrix LABoratory) is a high-level programming language and environment designed
primarily for numerical computation, data analysis, algorithm development, and visualization. It is widely
used in fields such as engineering, physics, finance, and mathematics.

Key Features of MATLAB:


1. Matrix-Based Language: MATLAB's core strength lies in its ability to handle and perform
operations on matrices and arrays. Everything in MATLAB is treated as an array or matrix, making it
easy to manipulate large datasets.
2. Interactive Environment: MATLAB provides an interactive environment where users can write
code, run it, and see the results immediately. This makes it ideal for exploration and iterative
development.
3. Built-in Functions: MATLAB comes with an extensive library of built-in functions that cover a
wide range of applications, from basic arithmetic to advanced mathematical operations like linear
algebra, optimization, and signal processing.
4. Visualization: MATLAB excels at plotting and visualizing data. You can create 2D and 3D plots,
graphs, histograms, surface plots, etc., with just a few lines of code. This feature is particularly useful
in understanding complex datasets.
5. Toolboxes: MATLAB has many specialized toolboxes for specific applications like image
processing, machine learning, control systems, and statistics. These toolboxes provide ready-made
functions that can save time and effort.
6. Extensibility: MATLAB can interface with other languages like C, C++, Java, and Python. It also
supports integration with hardware like sensors and cameras, making it useful for both academic
research and industrial applications.

Basic Concepts in MATLAB


1. Variables and Data Types: MATLAB supports various data types, including:
o Arrays: The fundamental data type in MATLAB, allowing you to store numbers in a grid-
like structure.
o Matrices: A two-dimensional array, which is key to MATLAB's capabilities.
o Strings: Text can be stored as strings and manipulated.
o Structures: Used to store collections of different data types under one name.
2. Operations and Functions:
o Basic arithmetic operations can be performed using standard operators like +, -, *, /, ^.
o Functions are defined using the function keyword, and MATLAB also supports anonymous
functions for one-liner functions.
Prepared by: Mr Thanmay J S, Assistant Professor, Bio-Medical & Robotics Engineering, UoM, SoE, Mysore 57006
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
3. Scripts and Functions:
o Scripts are files containing a sequence of MATLAB commands. They don't accept inputs or
return outputs.
o Functions are similar to scripts but can accept inputs and return outputs, allowing for
modular code.
4. Control Flow: MATLAB supports traditional programming constructs such as loops (for, while),
conditional statements (if, else, switch), and error handling (try, catch).
5. Plotting: MATLAB's plotting functions allow you to easily create visualizations:
o plot(): For creating 2D plots.
o surf(): For 3D surface plots.
o bar(): For bar charts.
o hist(): For histograms.

MATLAB Workflow
1. Develop Code: Write scripts or functions in the MATLAB editor or command window.
2. Run and Debug: Execute your code and view the output in the Command Window.
3. Analyze Data: Perform calculations, manipulate data, and visualize results.
4. Optimize: Refactor and optimize code for efficiency, particularly for large datasets.
5. Deploy: You can generate standalone applications, integrate with other software, or deploy
algorithms to hardware.

Applications of MATLAB
1. Engineering: Modeling physical systems, designing control systems, signal processing, etc.
2. Finance: Data analysis, modeling financial systems, risk management.
3. Image and Video Processing: Analyzing images, detecting patterns, and enhancing visuals.
4. Machine Learning: Training models, classification, clustering, and neural networks.

Prepared by: Mr Thanmay J S, Assistant Professor, Bio-Medical & Robotics Engineering, UoM, SoE, Mysore 57006
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Experiment 01
Aim: Execute a Program to understand different modes of input/output operations on numerical data and
character strings
Below is a MATLAB program that demonstrates various input/output operations, including:
1. Reading numerical data from the user using input().
2. Reading a string input using input() with the 's' flag for strings.
3. Writing numerical data to the command window using disp() and fprintf().
4. Writing character strings to the command window using disp() and fprintf().
5. Reading from a file using fopen(), fscanf(), and fgets().
6. Writing to a file using fopen() and fprintf().

The program for different modes of input/output operations on numerical data and character strings will
follow these steps:
1. Prompt the user to input a numerical value and a string.
2. Display these inputs to the command window.
3. Save the inputs to a file.
4. Read the data from the file and display it.
5. Use various I/O functions like input(), disp(), fprintf(), and file handling functions.

A. % Numerical Input from User


num_input = input('Enter a numerical value: ');
% Get numerical input from user
disp(['You entered the number: ', num2str(num_input)]);
% Display the number using disp()
% Output the numerical data with formatted text using fprintf()
fprintf('Formatted numerical output using fprintf(): %.2f\n', num_input);
end

B. % String Input from User


str_input = input('Enter a string: ', 's');
% Get string input from user
disp(['You entered the string: ', str_input]);
% Display the string using disp()
% Output the string with formatted text using fprintf()
fprintf('Formatted string output using fprintf(): %s\n', str_input);
end
Prepared by: Mr Thanmay J S, Assistant Professor, Bio-Medical & Robotics Engineering, UoM, SoE, Mysore 57006
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Practice Programs:
A.

B.

Student Signature Staff Signature

Prepared by: Mr Thanmay J S, Assistant Professor, Bio-Medical & Robotics Engineering, UoM, SoE, Mysore 57006
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Experiment 02
Aim: Execute a Programs to define and perform different operations on vector.

A. Adding Vectors

% Define Row and Column Vectors

row_vector = [1, 2, 3, 4, 5]; % Row vector

column_vector = [1; 2; 3; 4; 5]; % Column vector

% Addition of Vectors; Note: two row vectors of the same size

% Input another row vector and apply Element-wise addition

row_vector2 = [6, 7, 8, 9, 10];

result_add = row_vector + row_vector2;

%Display the Results

disp('Result of adding two row vectors:');

disp(result_add);

B. Scalar Multiplication

% Multiply each element of the vector by a scalar

scalar = 3;

% Scalar multiplication

result_scalar_mult = scalar * row_vector;

%Display the Results

disp('Result of scalar multiplication:');

disp(result_scalar_mult);

C. Multiply two Vectors

% Multiply two vectors element by element (requires same size vectors), Element-wise multiplication

result_elementwise_mult = row_vector .* row_vector2;

disp('Result of element-wise multiplication (Hadamard product):');

disp(result_elementwise_mult);

Prepared by: Mr Thanmay J S, Assistant Professor, Bio-Medical & Robotics Engineering, UoM, SoE, Mysore 57006
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
D. Vector Dot Product

% Dot product of two vectors

dot_product = dot(row_vector, row_vector2);

% Dot product Display

disp('Dot product of two vectors:');

disp(dot_product);

E. Cross Product (For 3D Vectors)

% Cross product works only for 3D vectors

vector1 = [1, 2, 3];

vector2 = [4, 5, 6];

% Cross product

cross_product = cross(vector1, vector2);

% Display Cross Products

disp('Cross product of two 3D vectors:');

disp(cross_product);

F. Magnitude (Norm) of a Vector

% Magnitude (Euclidean norm)

magnitude = norm(row_vector);

% Display the Magnitude

disp('Magnitude of the row vector:');

disp(magnitude);

G. Transpose of a Vector

% Transpose the row vector to make it a column vector using Transpose operator

transpose_row_vector = row_vector.';

% Display Transposed Results

disp('Transpose of the row vector (making it a column vector):');

disp(transpose_row_vector);

Prepared by: Mr Thanmay J S, Assistant Professor, Bio-Medical & Robotics Engineering, UoM, SoE, Mysore 57006
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Practice Program:
A.

B.

C.

D.

E.

F.

G.

Signature of Student Staff Signature


Prepared by: Mr Thanmay J S, Assistant Professor, Bio-Medical & Robotics Engineering, UoM, SoE, Mysore 57006
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Experiment 03
Aim: Execute a Programs to understand the basic operations on matrix.

% Define two matrices


A = [1, 2, 3; 4, 5, 6; 7, 8, 9]; % 3x3 matrix
B = [9, 8, 7; 6, 5, 4; 3, 2, 1]; % Another 3x3 matrix

1. Matrix Addition
matrix_add = A + B; % Add two matrices
disp('Matrix Addition (A + B):');
disp(matrix_add);

2. Matrix Subtraction
matrix_sub = A - B; % Subtract matrix B from matrix A
disp('Matrix Subtraction (A - B):');
disp(matrix_sub);

3. Matrix Multiplication (Dot Product)


matrix_mult = A * B; % Matrix multiplication (dot product)
disp('Matrix Multiplication (A * B):');
disp(matrix_mult);

4. Element-wise Multiplication (Hadamard Product)


elementwise_mult = A .* B; % Element-wise multiplication
disp('Element-wise Multiplication (A .* B):');
disp(elementwise_mult);

5. Matrix Transpose
matrix_transpose = A.'; % Transpose of matrix A
disp('Transpose of Matrix A:');
disp(matrix_transpose);

6. Determinant of a Matrix
determinant_A = det(A); % Calculate the determinant of matrix A
disp('Determinant of Matrix A:');
disp(determinant_A);

Prepared by: Mr Thanmay J S, Assistant Professor, Bio-Medical & Robotics Engineering, UoM, SoE, Mysore 57006
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
7. Inverse of a Matrix
inverse_A = inv(A); % Calculate the inverse of matrix A
disp('Inverse of Matrix A:');
disp(inverse_A);

8. Matrix Size
matrix_size_A = size(A); % Get the size of matrix A
disp('Size of Matrix A:');
disp(matrix_size_A);

9. Identity Matrix
identity_matrix = eye(3); % Create a 3x3 identity matrix
disp('3x3 Identity Matrix:');
disp(identity_matrix);

10. Scalar Multiplication


scalar = 2;
scalar_mult = scalar * A; % Multiply matrix A by a scalar
disp('Matrix A multiplied by scalar 2:');
disp(scalar_mult);
Practice Program:
1.

2.

Prepared by: Mr Thanmay J S, Assistant Professor, Bio-Medical & Robotics Engineering, UoM, SoE, Mysore 57006
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
3.

4.

5.

6.

7.

8.

Signature of Student Staff Signature


Prepared by: Mr Thanmay J S, Assistant Professor, Bio-Medical & Robotics Engineering, UoM, SoE, Mysore 57006
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Experiment 04
Aim: Write a Program to find the roots of a quadratic equation

A quadratic equation is of the form:

where a, b, and c are coefficients, and x represents the variable. The roots (solutions) of a quadratic equation
can be found using the quadratic formula:

% Prompt the user to enter the coefficients of the quadratic equation


a = input('Enter the coefficient a: ');
b = input('Enter the coefficient b: ');
c = input('Enter the coefficient c: ');
% Calculate the discriminant (b^2 - 4ac)
discriminant = b^2 - 4*a*c;
% Check the discriminant to determine the nature of the roots; if Condition 1 is (>0 )
if discriminant > 0 % Two real and distinct roots
root1 = (-b + sqrt(discriminant)) / (2*a);
root2 = (-b - sqrt(discriminant)) / (2*a);
disp('The equation has two real and distinct roots:');
disp(['Root 1 = ', num2str(root1)]);
disp(['Root 2 = ', num2str(root2)]);
% Check the discriminant to determine the nature of the roots; if Condition 1 is (=0)
elseif discriminant == 0 % One real and repeated root
root = -b / (2*a);
disp('The equation has one real and repeated root:');
disp(['Root = ', num2str(root)]);
% Check the last Condition 3 is (<0)
else % Complex roots
real_part = -b / (2*a);
imaginary_part = sqrt(-discriminant) / (2*a);
disp('The equation has two complex roots:');
disp(['Root 1 = ', num2str(real_part), ' + ', num2str(imaginary_part), 'i']);
disp(['Root 2 = ', num2str(real_part), ' - ', num2str(imaginary_part), 'i']);
end

Prepared by: Mr Thanmay J S, Assistant Professor, Bio-Medical & Robotics Engineering, UoM, SoE, Mysore 57006
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Practice Program:
1.

Signature of Student Staff Signature

Prepared by: Mr Thanmay J S, Assistant Professor, Bio-Medical & Robotics Engineering, UoM, SoE, Mysore 57006
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Experiment 05
Aim: Program to understand different arithmetic operators

% Define two numbers (scalars)


a = 10;
b = 5;
1. Addition
addition = a + b;
disp('Addition (a + b):');
disp(addition);
2. Subtraction
subtraction = a - b;
disp('Subtraction (a - b):');
disp(subtraction);
3. Multiplication
multiplication = a * b;
disp('Multiplication (a * b):');
disp(multiplication);
4. Division (Scalar Division)
division = a / b;
disp('Division (a / b):');
disp(division);
5. Power (Exponentiation)
power = a^b; % a raised to the power of b
disp('Exponentiation (a^b):');
disp(power);
6. Square root of a number
% Check if the number is non-negative, as square roots of negative numbers are complex
if a >= 0 % Calculate the square root using the sqrt() function
square_root = sqrt(a);
disp(['The square root of ', a), ' is: ', num2str(square_root)]);
else
% Display Error
disp('Error: The number must be non-negative to calculate the square root.');
end

Prepared by: Mr Thanmay J S, Assistant Professor, Bio-Medical & Robotics Engineering, UoM, SoE, Mysore 57006
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Practice Program:

Signature of Student Staff Signature

Prepared by: Mr Thanmay J S, Assistant Professor, Bio-Medical & Robotics Engineering, UoM, SoE, Mysore 57006
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Experiment 06
Aim: To Execute simple Program to understand different logical operations

% Define two logical variables (1 for true, 0 for false)


% A is true (1)
A = 1;
% B is false (0)
B = 0;
% Display the values of A and B
disp(['A = ', num2str(A)]);
disp(['B = ', num2str(B)]);

1. AND operation (A AND B)


% & is the logical AND operation
and_result = A & B;
disp(['A AND B = ', num2str(and_result)]);
% Expected output: 0 (false)

2. OR operation (A OR B)
% | is the logical OR operation
or_result = A | B;
disp(['A OR B = ', num2str(or_result)]);
% Expected output: 1 (true)

3. NOT operation (NOT A)


% ~ is the logical NOT operation (negation)
not_result = ~A;
disp(['NOT A = ', num2str(not_result)]);
% Expected output: 0 (false)

4. XOR operation (A XOR B)


% xor() performs exclusive OR
xor_result = xor(A, B);
disp(['A XOR B = ', num2str(xor_result)]);
% Expected output: 1 (true)

Prepared by: Mr Thanmay J S, Assistant Professor, Bio-Medical & Robotics Engineering, UoM, SoE, Mysore 57006
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
5. Comparison operations
a) Equal comparison (A = = B)
equal_result = (A == B);
disp(['A == B: ', num2str(equal_result)]);
% Expected output: 0 (false)

b) Not Equal Comparison (A ~= B)


not_equal_result = (A ~= B);
disp(['A ~= B: ', num2str(not_equal_result)]);
% Expected output: 1 (true)

c) Greater than comparison (A > B)


greater_than_result = (A > B);
disp(['A > B: ', num2str(greater_than_result)]);
% Expected output: 1 (true)

d) Less than comparison (A < B)


less_than_result = (A < B);
disp(['A < B: ', num2str(less_than_result)]);
% Expected output: 0 (false)

Data Functions Output


A=1 A AND B =
……………….
B=0 A OR B =
……………….
NOT A =
……………….
A XOR B =
……………….
A == B =
……………….
A ~= B =
……………….
A>B=
……………….
A<B=
……………….

Signature of Student Staff Signature


Prepared by: Mr Thanmay J S, Assistant Professor, Bio-Medical & Robotics Engineering, UoM, SoE, Mysore 57006
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Experiment 07
Aim: To Execute simple Program to understand different set operators
% Define two sets using arrays
A = [1, 2, 3, 4, 5]; % Set A
B = [4, 5, 6, 7, 8]; % Set B
% Display the sets A and B
disp('Set A:');
disp(A);
disp('Set B:');
disp(B);

1. Union (A ∪ B)
union_result = union(A, B);
disp('Union of A and B (A ∪ B):');
disp(union_result); % Expected output: [1, 2, 3, 4, 5, 6, 7, 8]

2. Intersection (A ∩ B)
intersection_result = intersect(A, B);
disp('Intersection of A and B (A ∩ B):');
disp(intersection_result); % Expected output: [4, 5]

3. Difference (A - B)
difference_result = setdiff(A, B);
disp('Difference of A and B (A - B):');
disp(difference_result); % Expected output: [1, 2, 3]

4. Symmetric Difference (A Δ B)
symmetric_diff_result = setxor(A, B);
disp('Symmetric Difference of A and B (A Δ B):');
disp(symmetric_diff_result); % Expected output: [1, 2, 3, 6, 7, 8]

5. Set Membership (Is each element of A in B?)


is_member_result = ismember(A, B);
disp('Set membership (Is each element of A in B?):');
disp(is_member_result); % Expected output: [0, 0, 0, 1, 1] (false for 1, 2, 3, true for 4, 5)

Prepared by: Mr Thanmay J S, Assistant Professor, Bio-Medical & Robotics Engineering, UoM, SoE, Mysore 57006
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Output:

Set A: […………………………………….]

Set B: […………………………………….]

Union of A and B (A ∪ B):

[……………………………………………………………………………….]

Intersection of A and B (A ∩ B):

[……………………………………………………………………………….]

Difference of A and B (A - B):

[……………………………………………………………………………….]

Symmetric Difference of A and B (A Δ B):

[……………………………………………………………………………….]

Set membership (Is each element of A in B?):

[……………………………………………………………………………….]

Signature of Student Staff Signature


Prepared by: Mr Thanmay J S, Assistant Professor, Bio-Medical & Robotics Engineering, UoM, SoE, Mysore 57006
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Experiment 08
Aim: Execute a Program to define a user-defined function and call this function in the main program to realize
the task.

Task:
The task here is to define a function that computes the area of a circle based on a given radius. The main
program will ask the user for the radius and then call the user-defined function to calculate and display the
area of the circle.
Step 1: Create the User-Defined Function
Note: Save this function as circleArea.m.
% Function to calculate the area of a circle
% This function takes the radius as input and returns the area
function area = circleArea(radius)
% Formula for the area of a circle: A = pi * r^2
area = pi * radius^2;
end

Step 2: Main Program


This is the main script that will call the circleArea function.

% Main Program to Calculate the Area of a Circle


% Ask the user for the radius of the circle
radius = input('Enter the radius of the circle: ');
% Call the user-defined function to calculate the area
area = circleArea(radius);
% Display the result
disp(['The area of the circle with radius ', num2str(radius), ' is: ', num2str(area)]);

Output:
Enter the radius of the circle: …………………….

The area of the circle with radius ……………………. is: …………………….

Signature of Student Staff Signature

Prepared by: Mr Thanmay J S, Assistant Professor, Bio-Medical & Robotics Engineering, UoM, SoE, Mysore 57006
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Experiment 09
Aim: Writing and Executing the Programs to understand basic algebra functions.

understand basic algebra functions such as solving linear equations, finding roots of polynomials, matrix
operations, and working with symbolic algebra can be computed using Matlab, the following programs are
the examples:
1. Solving a System of Linear Equations

% Define the coefficient matrix A and the right-hand side vector b


A = [2, 3; 4, -1]; % Coefficients of x and y
b = [5; 3]; % Right-hand side of the equations
% Solve the system of equations using the backslash operator
solution = A \ b;
% Display the solution
disp('The solution to the system of equations is:');
disp(['x = ', num2str(solution(1))]);
disp(['y = ', num2str(solution(2))]);
The solution to the above equations is:
x = ………………………..
y = ………………………..

2. Finding the Roots of a Polynomial


In this example, we will find the roots of a polynomial

% Define the coefficients of the polynomial


coefficients = [1, -5, 6]; % Coefficients of x^2 - 5x + 6
% Find the roots of the polynomial using the roots function
roots_of_polynomial = roots(coefficients);
% Display the roots
disp('The roots of the polynomial are:');
disp(roots_of_polynomial);
The solution to the above equations is:
The roots of the polynomial are:
…………………………….
…………………………….
Prepared by: Mr Thanmay J S, Assistant Professor, Bio-Medical & Robotics Engineering, UoM, SoE, Mysore 57006
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
3. Matrix Operations (Addition, Multiplication, and Inverse)
In this example, we perform basic matrix operations such as addition, multiplication, and finding the inverse
of a matrix.
% Define two matrices A and B
A = [1, 2; 3, 4];
B = [5, 6; 7, 8];
% Matrix addition
C = A + B;
% Matrix multiplication
D = A * B;
% Matrix inverse (if A is invertible)
A_inv = inv(A);

% Display the results


disp('Matrix A:');
disp(A);
disp('Matrix B:');
disp(B);
disp('Matrix A + B:');
disp(C);
disp('Matrix A * B:');
disp(D);
disp('Inverse of Matrix A:');
disp(A_inv);

Output
Matrix A: Matrix B: Matrix A + B:

….. …… ….. …… ….. ……

….. …… ….. …… ….. ……

Matrix A * B: Inverse of Matrix A:

….. …… ….. ……

….. …… ….. ……

Signature of Student Staff Signature


Prepared by: Mr Thanmay J S, Assistant Professor, Bio-Medical & Robotics Engineering, UoM, SoE, Mysore 57006
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Experiment 10
Aim: Programs to create and manipulate cell arrays.

1. Create a cell array with different types of data

myCellArray = {1, 'hello', [1, 2, 3], magic(3)};

% Display the cell array

disp('Original Cell Array:');

disp(myCellArray);

2. Access the first element (a number)

firstElement = myCellArray{1};

disp(['First Element (number): ', num2str(firstElement)]);

3. Access the second element (a string)

secondElement = myCellArray{2};

disp(['Second Element (string): ', secondElement]);

4. Access the third element (a numeric array)

thirdElement = myCellArray{3};

disp('Third Element (numeric array):');

disp(thirdElement);

5. Access the fourth element (a magic square matrix)

fourthElement = myCellArray{4};

disp('Fourth Element (magic square matrix):');

disp(fourthElement);

Prepared by: Mr Thanmay J S, Assistant Professor, Bio-Medical & Robotics Engineering, UoM, SoE, Mysore 57006
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
6. Modify the first element (change number)

myCellArray{1} = 42;

disp('Modified Cell Array (First Element Changed):');

disp(myCellArray);

7. Modify the second element (change string)

myCellArray{2} = 'world';

disp('Modified Cell Array (Second Element Changed):');

disp(myCellArray);

8. Add a new element to the end (a logical value)

myCellArray{end+1} = true;

disp('Cell Array after adding new element (logical value):');

disp(myCellArray);

9. Nested Cell Array Example

% Create a nested cell array

nestedCell = {1, 2, {3, 4}};

disp('Nested Cell Array:');

disp(nestedCell);

% Accessing an element from the nested cell array

nestedElement = nestedCell{3}{2}; % Accessing the second element inside the third cell

disp(['Nested Element: ', num2str(nestedElement)]);

Prepared by: Mr Thanmay J S, Assistant Professor, Bio-Medical & Robotics Engineering, UoM, SoE, Mysore 57006
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Output:

Original Cell Array:

………………………………………………………………………………

First Element (number): ………………………

Second Element (string): ………………………

Third Element (numeric array): ………………………

Fourth Element (magic square matrix):

………………………

………………………

………………………

Modified Cell Array (First Element Changed):

………………………………………………………………………………

Modified Cell Array (Second Element Changed):

………………………………………………………………………………

Cell Array after adding new element (logical value):

………………………………………………………………………………

Modified Cell Array after multiplying numeric elements by 2:

………………………………………………………………………………

Nested Cell Array:

………………………………………………………………………………

Nested Element: 4

………………………………………………………………………………

Signature of Student Staff Signature

Prepared by: Mr Thanmay J S, Assistant Professor, Bio-Medical & Robotics Engineering, UoM, SoE, Mysore 57006
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Experiment 11
Aim: Create a Matlab Program to generate and plot and subplot 2D and 3D data

1. Generate 2D Data (Line Plot)


x = linspace(0, 10, 100); % Create 100 points between 0 and 10
y = sin(x); % y = sin(x)

2. Generate 3D Data (Surface Plot)


[X, Y] = meshgrid(-5:0.5:5, -5:0.5:5); % Create a grid of points for X and Y
Z = sin(sqrt(X.^2 + Y.^2)); % Z = sin(sqrt(X^2 + Y^2))

3. Create a figure window with 2 subplots


figure;

4. First subplot: 2D line plot


subplot(1, 2, 1); % Divide the figure into 1 row, 2 columns, and plot in the 1st section
plot(x, y, 'b', 'LineWidth', 2); % Plot y = sin(x) with blue line
title('2D Plot: y = sin(x)');
xlabel('x');
ylabel('y');
grid on;

5. Second subplot: 3D surface plot


subplot(1, 2, 2); % Plot in the 2nd section of the figure
surf(X, Y, Z); % Create a 3D surface plot
title('3D Surface Plot: Z = sin(sqrt(X^2 + Y^2))');
xlabel('X');
ylabel('Y');
zlabel('Z');
colorbar; % Display color bar to represent Z values
shading interp; % Interpolate the color to make the surface smooth
grid on;
% Adjust layout to prevent overlapping of titles/labels
tight_layout;

Prepared by: Mr Thanmay J S, Assistant Professor, Bio-Medical & Robotics Engineering, UoM, SoE, Mysore 57006
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Practice Program:

Signature of Student Staff Signature

Prepared by: Mr Thanmay J S, Assistant Professor, Bio-Medical & Robotics Engineering, UoM, SoE, Mysore 57006
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Experiment 12
Aim: Show a sample Program to understand the control structures: if, if-else and switch

1. if Control Structure

The if statement is used to execute code only if a specified condition is true.

% Given number

number = 7;

% Check if the number is positive

if number > 0

disp('The number is positive');

end

2. if-else Control Structure

The if-else statement is used when you want to execute one block of code if a condition is true, and another

block if it is false.

% Given number

number = -3;

% Check if the number is positive or negative

if number > 0

disp('The number is positive');

else

disp('The number is negative');

end

3. switch Control Structure

The switch statement is used to execute different blocks of code based on the value of a variable.

% Given day of the week

day = 'Tuesday';

% Check which day it is using switch

switch day

Prepared by: Mr Thanmay J S, Assistant Professor, Bio-Medical & Robotics Engineering, UoM, SoE, Mysore 57006
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
case 'Monday'

disp('Start of the week');

case 'Tuesday'

disp('Second day of the week');

case 'Wednesday'

disp('Middle of the week');

case 'Thursday'

disp('Almost there!');

case 'Friday'

disp('End of the work week');

otherwise

disp('Weekend!');

end

Practice Program:

Signature of Student Staff Signature


Prepared by: Mr Thanmay J S, Assistant Professor, Bio-Medical & Robotics Engineering, UoM, SoE, Mysore 57006
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Experiment 13
Aim: Generate a Program to understand the loop structures: while and for

1. while Loop Structure

The while loop repeatedly executes a block of code as long as the given condition remains true.

Example: Printing numbers from 1 to 5 using a while loop

% Initialize the counter

counter = 1;

% Execute the loop as long as the counter is less than or equal to 5

while counter <= 5

disp(['The current number is: ', num2str(counter)]);

counter = counter + 1; % Increment the counter

end

2. for Loop Structure

The for loop is used to iterate over a specified number of times. It is commonly used when the number of

iterations is known beforehand.

Example: Printing the squares of numbers from 1 to 5 using a for loop

% Loop from 1 to 5

for i = 1:5

square = i^2; % Calculate the square of the number

disp(['The square of ', num2str(i), ' is: ', num2str(square)]);

end

Prepared by: Mr Thanmay J S, Assistant Professor, Bio-Medical & Robotics Engineering, UoM, SoE, Mysore 57006
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Output

1. while Loop Output:

The current number is: ……..

The current number is: ……..

The current number is: ……..

The current number is: ……..

The current number is: ……..

2. for Loop Output:

The square of 1 is: ……..

The square of 2 is: ……..

The square of 3 is: ……..

The square of 4 is: ……..

The square of 5 is: ……..

Signature of Student Staff Signature


Prepared by: Mr Thanmay J S, Assistant Professor, Bio-Medical & Robotics Engineering, UoM, SoE, Mysore 57006
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Experiment 14
Aim: Write a Program to find the roots of a given polynomial and to construct the polynomial from the

given roots of the polynomial.

Part 1: Finding roots from a given polynomial


% Define the coefficients of the polynomial (from highest to lowest degree)
% Example: Polynomial 𝑥 3 − 6 𝑥 2 + 11𝑥 − 6

coefficients = [1 -6 11 -6];
% Finding the roots of the polynomial
roots_of_polynomial = roots(coefficients);
disp('Roots of the polynomial:');
disp(roots_of_polynomial);

Part 2: Constructing the polynomial from the roots


% Given the roots, reconstruct the polynomial
% The poly function returns the coefficients of the polynomial from its roots
reconstructed_coefficients = poly(roots_of_polynomial);
disp('Reconstructed polynomial coefficients:');
disp(reconstructed_coefficients);

Practice Program:

Signature of Student Staff Signature

Prepared by: Mr Thanmay J S, Assistant Professor, Bio-Medical & Robotics Engineering, UoM, SoE, Mysore 57006
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Viva Question and Answers
1. What is MATLAB?
Answer: MATLAB stands for "Matrix Laboratory." It is a high-level programming language used primarily
for numerical computation, data analysis, visualization, and algorithm development. MATLAB's core
functionality revolves around matrix operations.

2. What are the basic data types in MATLAB?


Answer: The basic data types in MATLAB are:
• Numeric: Represents numbers, including integers and floating-point numbers.
• Character: Represents text or strings.
• Logical: Represents true (1) or false (0).
• Cell Arrays: Containers for data of varying types and sizes.
• Structures: Store data in fields.

3. How do you define a matrix in MATLAB?


Answer: A matrix is defined using square brackets [ ]. Elements are separated by spaces or commas, and
rows are separated by semicolons. Example:
A = [1, 2, 3; 4, 5, 6; 7, 8, 9];

4. What is the purpose of the clc command in MATLAB?


Answer: The clc command clears the command window, removing all text and outputs displayed in the
window.

5. What is the use of clear in MATLAB?


Answer: The clear command removes variables from the workspace. It frees up memory by clearing
specified variables or all variables. Example:
clear x; % Clears variable x

6. What does disp() do in MATLAB?


Answer: The disp() function displays text or the value of variables in the command window. Example:
disp('Hello, World!');

Prepared by: Mr Thanmay J S, Assistant Professor, Bio-Medical & Robotics Engineering, UoM, SoE, Mysore 57006
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
7. What is the difference between = and == in MATLAB?
Answer:
• = is the assignment operator, used to assign a value to a variable.
• == is the equality operator, used to compare whether two values are equal.

8. How do you generate a vector from 1 to 10 in MATLAB?


Answer: You can use the colon operator to generate a vector.
v = 1:10;

9. What is the purpose of the size() function in MATLAB?


Answer: The size() function returns the dimensions (rows and columns) of an array or matrix. Example:
A = [1, 2; 3, 4];
sz = size(A); % Returns [2, 2] for a 2x2 matrix

10. How can you find the roots of a polynomial in MATLAB?


Answer: You can use the roots() function to find the roots of a polynomial given its coefficients. Example:
p = [1, -6, 11, -6]; % Coefficients of the polynomial x^3 - 6x^2 + 11x - 6
r = roots(p); % Finds the roots of the polynomial

11. What are loops in MATLAB?


Answer: Loops allow repeated execution of a block of code. The two main types of loops in MATLAB are:
• for loop: Executes a block of code a specified number of times.
• while loop: Executes a block of code while a condition is true. Example:
for i = 1:5
disp(i); % Displays 1 to 5
end

12. How do you create a function in MATLAB?


Answer: A function in MATLAB is created by defining it in a separate file with a .m extension. The syntax
is:
function output = function_name(input)
% Function code here
End
Prepared by: Mr Thanmay J S, Assistant Professor, Bio-Medical & Robotics Engineering, UoM, SoE, Mysore 57006
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
13. What is an array in MATLAB?
Answer: An array is a collection of values (numbers, strings, etc.) stored in a single variable. In MATLAB,
arrays can be one-dimensional (vectors) or multi-dimensional (matrices).

14. How can you plot a graph in MATLAB?


Answer: You can plot a graph using the plot() function. Example:
x = 0:0.1:10;
y = sin(x);
plot(x, y); % Plots the sine wave

15. What is the difference between a script and a function in MATLAB?


Answer:
• Script: A script is a collection of MATLAB commands saved in a .m file. It does not accept inputs or
return outputs.
• Function: A function is a reusable block of code that can accept inputs and return outputs. It is
defined in a separate .m file with a function signature.
These questions cover some of the basic concepts in MATLAB, and they can help you understand
fundamental MATLAB programming techniques.

Prepared by: Mr Thanmay J S, Assistant Professor, Bio-Medical & Robotics Engineering, UoM, SoE, Mysore 57006

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy