Matlab File 01
Matlab File 01
Description : MATLAB stands for Matrix Laboratory. It is a high-performance language that is used for
technical computing. It was developed by Cleve Molar of the company MathWorks.Inc in the year 1984.It
is written in C, C++, Java. It allows matrix manipulations, plotting of functions, implementation of
algorithms and creation of user interfaces.
1. Using Command Window: Only one statement can be typed and executed at a time. It
executes the statement when the enter key is pressed. This is mostly used for simple
calculations. Note: ans is a default variable created by MATLAB that stores the output of the
given computation.
2. Using Editor: Multiple lines of code can be written here and only after pressing the run button
(or F5) will the code be executed. It is always a good practice to write clc, clear and close all in
the beginning of the program.Note: Statements ending with a semicolon will not be displayed
in the command window, however, their values will be displayed in the workspace. Any
statement followed by % in MATLAB is considered as a comment
3. Vector Operations: Operations such as addition, subtraction, multiplication and division can
be done using a single command instead of multiple loops
1. Mathematics and Computation: MATLAB offers a rich set of mathematical functions for linear algebra,
statistics, optimization, and differential equations. It allows users to perform complex calculations efficiently,
making it a popular choice for engineers, scientists, and researchers.
2. Data Analysis and Visualization: With powerful plotting and visualization tools, MATLAB enables users
to explore and analyze data in various formats, including arrays, tables, and images. It supports customizable
plots, 2D and 3D visualizations, as well as interactive graphics for conveying insights from data.
3. Algorithm Development: MATLAB facilitates algorithm prototyping and development with its intuitive
syntax and extensive library of pre-built functions. Users can implement and test algorithms quickly, making
it ideal for signal processing, image processing, machine learning, and control system design.
4. Simulation and Modeling: MATLAB includes simulation capabilities for simulating dynamic systems,
such as mechanical, electrical, and biochemical systems. It supports simulation of continuous-time and
discrete-time models, enabling engineers to design and analyze complex systems before implementation.
5. Application Development: MATLAB can be used for developing standalone applications and graphical
user interfaces (GUIs) for deploying computational tools to end-users. It provides tools for building interactive
apps with buttons, sliders, and plots, allowing developers to create user-friendly interfaces for their MATLAB
programs.
7. Education and Research: MATLAB is widely used in academia for teaching and research purposes across
various disciplines, including engineering, physics, biology, and finance. Its easy-to-learn syntax and
extensive documentation make it accessible to students and researchers alike.
Overall, MATLAB's versatility and broad range of functionalities make it a valuable tool for professionals
and researchers in numerous fields, from engineering and science to finance and beyond. Its interactive nature,
combined with its extensive library of functions and toolboxes, makes it a preferred choice for tackling diverse
computational and data analysis challenges.
Using MATLAB offers several advantages across various fields and applications:
1. Easy to Learn and Use: MATLAB's syntax is designed to be intuitive and easy to learn, especially for
those with a background in mathematics or engineering. Its interactive environment allows users to quickly
test ideas and algorithms without needing to compile code.
2. Extensive Functionality: MATLAB provides a vast array of built-in functions and toolboxes for numerical
computation, data analysis, signal processing, image processing, optimization, machine learning, and more.
This extensive functionality reduces the need for writing code from scratch and accelerates development time.
3. Rich Visualization Tools: MATLAB offers powerful plotting and visualization capabilities, allowing users
to create high-quality 2D and 3D plots, animations, and interactive graphics. Visualization is crucial for
analyzing data and conveying insights effectively.
6. Algorithm Prototyping: MATLAB's interactive environment is well-suited for algorithm prototyping and
development. Users can quickly implement and test algorithms, iterate on designs, and refine solutions before
deploying them in production environments.
7. Community and Support: MATLAB has a large and active user community, which provides access to
resources, forums, and online tutorials. Additionally, MathWorks offers comprehensive documentation,
technical support, and training programs to help users get the most out of the software.
8. Integration with Other Tools: MATLAB can easily integrate with other programming languages, tools,
and hardware platforms. It supports interoperability with C/C++, Python, Java, and other languages, as well
as interfaces to hardware devices and external software packages.
9. Parallel Computing and Deployment: MATLAB supports parallel computing to leverage multi-core
processors, clusters, and cloud computing resources for accelerating computationally intensive tasks.
Additionally, MATLAB Compiler enables users to deploy MATLAB code as standalone applications or
shared libraries for distribution to end-users.
10. Education and Research: MATLAB is widely used in academia for teaching and research purposes due
to its accessibility, versatility, and broad range of functionalities. Its adoption in educational institutions
prepares students for careers in industry and research.
EXPERIMENT - 2
Aim : Find addition, subtraction, multiplication and division of two matrices usingMATLAB.
Description :-
Defining a Matrix:
In MATLAB, a matrix is a rectangular array of numbers, symbols, or expressions arranged in rows and
columns. It's a fundamental data structure used for storing and manipulating numerical data.
Matlab
MATLAB provides a powerful and versatile environment for performing various mathematical
operations. Among these, fundamental arithmetic operations like addition, subtraction, multiplication,
and division form the building blocks for more complex calculations.
● Addition (+): This operator combines two numerical values or matrices of the same size,
element-wise. For example, 2 + 3 returns 5, and [1 2; 3 4] + [5 6; 7 8] results in [6 8; 10 12].
● Subtraction (-): This operator finds the difference between two numbers or subtracts
corresponding elements from matrices of the same dimensions. For example, 5 - 2 returns 3,and
[10 20; 30 40] - [5 10; 15 20] gives [5 10; 15 20].
● Multiplication (*): Multiplication in MATLAB can have different meanings depending onthe
context.
Aim : Verify whether the given matrix is singular or non singular and compute the inverse if applicable
Description :-
A non-singular matrix is a square matrix whose determinant is not equal to zero.The non-singular matrix
condition of it being a non singular matrix is the determinant of this matrix A is anon zero value. |A| =|ad
- bc| ≠ 0.
• Inverse of Matrix
Just like a number has it’s reciprocal, even a matrix has an inverse. If we consider a matrix A, we denote
its inverse as A-1. The inverse of amatrix is another matrix that, when multiplied by the given matrix,
yields the multiplicative identity.
For a matrix A, its inverse is A-1. And A.A-1 = I, where I is denotedas the identity matrix. In order
to find the inverse matrix, the square matrix must be non-singular and have a determinant value that is
not zero. Let us consider a 2×2 square matrix A.
The determinant of matrix A is denoted as ad-bc, and the value of the determinant should not be zero in
order for the inverse matrix of A to exist. A simple formula can be used to calculate the inverse of a 2×2
matrix. Furthermore, in order to obtain the inverse of a 3×3 matrix, we must first determine the
determinant and adjoint of the matrix.
Implementation:
Experiment-4
Aim: Sorting of 1-D and 2-D array and searching in an array/matrix. Also, list the set of numbers that obey a common
condition in an array/matrix using find( ).
Description:
Sorting Arrays: sorting rearranges array elements in a specific order:
1. Ascending (default): Smaller values come first.
2. Descending: Larger values come first.
● 1-D Arrays:
Sort(myArray) sorts myArray in ascending order. Sort(myArray, ‘descend’) sorts in descending order.
Example- (1-D array):
Example-(2-D Array):
● Sorting by columns:
● Sorting by Rows:
● Searching: searching an array means finding elements that you're interested in.
There are two main ways to search arrays in MATLAB:
1. Indexing: Use for finding elements at specific locations based on row and column positions.
Implementation:
2. find() function:More powerful for finding elements based on conditions. It returns indices of elements that
meet criteria using comparison operators or logical expressions.
Implementation:
Experiment-5
Aim: Solve simultaneous equations (maximum of three) using Cramer’s rule. [Simultaneous equations may be
obtained by applying KCL or KVL for a circuit and they can be solved for voltages or currents, respectively].
Description:
● Cramer's rule is a method for solving systems of linear equations that works by using determinants. It can be
used to solve systems of equations with up to three variables.
● Cramer's rule is a method for solving systems of linear equations with the same number of equations and
variables (up to three). Here's how it works:
A*X=B
where:
Cramer's rule expresses each solution variable as the quotient of two determinants:
● The determinant of a modified coefficient matrix where the constant term's column is replaced by the constants vector
for that variable.
● The determinant of the original coefficient matrix (A).
Implementation :
❖ Kirchhoff's Current Law (KCL) and Kirchhoff's Voltage Law (KVL) are fundamental principles for
analyzing electrical circuits. They can be used to create a system of equations that describe the relationships
between currents and voltages in a circuit.
Steps:
1. Define Variables:
o Let I be the current source current
o Let I1 be the current through R1
o Let I2 be the current through R2
2. Write KCL Equation:
o At the junction where the current source splits, I = I1 + I2
3. Solve in MATLAB:
EXPERIMENT - 6
Aim : a) Show that log10(A*B) = log10(A)+ log10(B) and log10(A/B)=log10(A)-log10(B) b) Plot the
voltage across capacitor during charging Vc=V0[1-e-(t/RC)]
Descriptions :- Plotting the voltage across a capacitor during charging is crucial in understanding its behavior
in an RC circuit. The equation Vc=V0[1-e^(-t/RC)] represents this voltage, where Vc is the voltage across the
capacitor at time t, V0 is the initial voltage, R is the resistance, C is the capacitance, and e is the base of the
natural logarithm. As time progresses, the voltage across the capacitor approaches V0 exponentially, with the
time constant RC determining the rate of charging. Plotting Vc against time provides insights into the charging
process, illustrating how the capacitor's voltage evolves over time until it reaches its steady-state value of V0.
Implementation (a):-
Implementation (b) :-
EXPERIMENT – 7
Aim : a) Plot a straight line for the given slope and intercept using different plot attributes. b) Differentiate
and integrate y=mx+c, separately, and display the results on the same plot
a) Plot a straight line for the given slope and intercept using different plot attributes:
In this part, we generate a straight line based on the equation 𝑦=𝑚𝑥+𝑐y=mx+c, where 𝑚m is the slope and
𝑐c is the intercept. We create an array of x values using linspace() function, then calculate the
corresponding y values for the line using the equation 𝑦=𝑚𝑥+𝑐y=mx+c.
We use the plot() function to plot the line with different plot attributes (colors and line styles) by specifying
different format strings ('b', 'r--', 'g-.', 'k:'). These format strings control the color and style of the lines in the
plot.
b) Differentiate and integrate 𝑦=𝑚𝑥+𝑐y=mx+c, separately, and display the results on the same plot:
For this part, we first define the symbolic variable 𝑥x using the syms function. Then, we define the function
𝑦=𝑚𝑥+𝑐y=mx+c symbolically using the symbolic variables.
We differentiate 𝑦y with respect to 𝑥x using the diff() function to find the derivative of the function.
Similarly, we integrate 𝑦y with respect to 𝑥x using the int() function to find the integral of the function.
After differentiating and integrating the function symbolically, we convert the resulting symbolic
expressions to MATLAB functions using the matlabFunction() function. This allows us to evaluate the
derivative and integral at different x values.
We generate a range of x values using linspace() and then evaluate the original function, its derivative, and
its integral at these x values. Finally, we plot all three functions on the same graph using the plot() function,
and add labels, titles, legends, and grid lines to make the plot clear and informative.
Implementation (a):-
Implementation (b) :-
Code:
% Define slope and intercept
m = 2;
c = 5;
x = linspace(0, 10, 100);
% Calculate corresponding y values
y = m*x + c;
% Plotting straight line with different plot attributes
figure;
subplot(2, 2, 1);
plot(x, y, '-'); % Default line style
title('Default Line Style');
subplot(2, 2, 2);
plot(x, y, '--r'); % Dashed red line
title('Dashed Red Line');
subplot(2, 2, 3);
plot(x, y, 'g-.'); % Dash-dot green line
title('Dash-dot Green Line');
subplot(2, 2, 4);
plot(x, y, ':m'); % Dotted magenta line
title('Dotted Magenta Line');
% Differentiate and integrate y=mx+c separately
syms x;
dy_dx = diff(m*x + c, x); % Differentiate
int_y = int(m*x + c, x); % Integrate
% Plotting differentiation and integration
figure;
fplot(m*x + c, 'b', 'LineWidth', 2); % Original function
hold on;
fplot(dy_dx, 'r--', 'LineWidth', 1.5); % Differentiated function
fplot(int_y, 'g-.', 'LineWidth', 1.5); % Integrated function
legend({'y=mx+c', 'dy/dx', 'Integral of y'}, 'Location', 'best');
title('Original Function, Differentiation, and Integration');
xlabel('x');
ylabel('y');
grid on;
hold off;
Output B:-
EXPERIMENT – 8
Aim : Integrate and differentiate sin(x) and display the results on the same plot in different colors. Also
display sin(x) on the same plot.
Description :- This MATLAB code integrates and differentiates the function \( \sin(x) \) symbolically using
the symbolic mathematics toolbox. It then calculates the corresponding values for each function over a range
of \( x \) values. By plotting these functions on the same plot with different colors and line styles, the effects
of differentiation and integration on the sine function are visually represented, aiding in understanding their
relationships and behaviors.
1.sin(x):
2. int(symbolic expression):
3. diff(x):
Aim: Compute mean, median, standard deviation and variance of a set of data using formulae and verify
using built-in functions.
Mean:
In statistics, the mean is one of the measures of central tendency, apart from the mode and median. Mean is
nothing but the average of the given set of values. It denotes the equal distribution of values for a given data
set. Mean is the average of the given numbers and is calculated by dividing the sum of given numbers by the
total number of numbers.
Mean = (Sum of all the observations/Total number of observations)
Example:
In a class there are 20 students and they have secured a percentage of 88, 82, 88, 85, 84, 80, 81, 82, 83, 85,
84, 74, 75, 76, 89, 90, 89, 80, 82, and 83.
Find the mean percentage obtained by the class.
Solution:
Mean = Total of percentage obtained by 20 students in class/Total number of students
= [88 + 82 + 88 + 85 + 84 + 80 + 81 + 82 + 83 + 85 + 84 + 74 + 75 + 76 + 89 + 90 + 89 + 80 + 82 + 83]/20
= 1660/20
= 83
Hence, the mean percentage of each student in the class is 83%.
Median:
Median is defined as the middle value in a given set of numbers or data. The middle value of the given data is
defined by a median.
Based on the definition, the formula to find the median of the dataset is given by:
If the given number of observations/data is odd, then the formula to calculate the median is:
Median = {(n+1)/2}th term
If the given number of observations is even, then the formula to find the median is given by:
Median = [(n/2)th term + {(n/2)+1}th term]/2
Where,
“n” is the number of observations.
Example:
In a class there are 20 students and they have secured a percentage of 88, 82, 88, 85, 84, 80, 81, 82, 83, 85,
84, 74, 75, 76, 89, 90, 89, 80, 82, and 83.
Find the median.
Solution:
To find the median, you first need to arrange the percentages in ascending order:
74, 75, 76, 80, 80, 81, 82, 82, 82, 83, 83, 84, 84, 85, 85, 88, 88, 89, 89, 90
Since there are 20 students, an even number, the median will be the average of the 10th and 11th values in the
sorted list:
Median = (83 + 83) / 2 = 83
So, the median percentage obtained by the class is 83.
Variance:
Variance is the measure of how notably a collection of data is spread out. If all the data values are identical,
then it indicates the variance is zero. All non-zero variances are considered to be positive. A little variance
represents that the data points are close to the mean, and to each other, whereas if the data points are highly
spread out from the mean and from one another indicates the high variance.
Variance Formula:
The population variance formula is given by:
Standard Deviation:
Standard Deviation is a measure which shows how much variation (such as spread, dispersion, spread,) from
the mean exists. The standard deviation indicates a “typical” deviation from the mean. It is a popular measure
of variability because it returns to the original units of measure of the data set. Like the variance, if the data
points are close to the mean, there is a small variation whereas the data points are highly spread out from the
mean, then it has a high variance. Standard deviation calculates the extent to which the values differ from the
average.
Standard Deviation Formula
The population standard deviation formula is given as:
Here,
σ = Population standard deviation
N = Number of observations in population
Xi = ith observation in the population
μ = Population mean
Similarly, the sample standard deviation formula is:
Here,
s = Sample standard deviation
n = Number of observations in sample
xi = ith observation in the sample
= Sample mean
Example:
In a class there are 20 students and they have secured a percentage of 88, 82, 88, 85, 84, 80, 81, 82, 83, 85,
84, 74, 75, 76, 89, 90, 89, 80, 82, and 83.
Find the standard deviation and variance obtained by the class.
Solution:
Inbuilt functions in MATLAB for finding:
1.Mean:
M = mean(A) returns the mean of the elements of A along the first array dimension whose size is greater than
1.
2.Median:
M = median(A) returns the median value of A.
3.Variance:
V = var(A) returns the variance of the elements of A along the first array dimension whose size is greater than
1. By default, the variance is normalized by N-1, where N is the number of observations.
4.Standard Deviation:
S = std(A) returns the standard deviation of the elements of A along the first array dimension whose size is
greater than 1. By default, the standard deviation is normalized by N-1, where N is the number of observations.
Example of the same data set with all calculations with inbuilt functions in MATLAB:
Output:
Experiment 10
Aim: Demonstrate (a) reading and display image, (b)converting color image to gray and black and-white and
plotting their histograms, and (c) conversion of image file formats.
A = imread(filename,fmt)
A = imread(___,idx)
A = imread(___,Name,Value)
[A,map] = imread(___)
[A,map,transparency] = imread(___)
Description
A = imread(filename) reads the image from the file specified by filename, inferring the
format of the file from its contents. If filename is a multi-image file, then imread reads the
first image in the file.
A = imread(filename,fmt) additionally specifies the format of the file with the standard file
extension indicated by fmt. If imread cannot find a file with the name specified by filename,
it looks for a file named filename.fmt.
A = imread(___,idx) reads the specified image or images from a multi-image file. This
syntax applies only to GIF, PGM, PBM, PPM, CUR, ICO, TIF, SVS, and HDF4 files. You
must specify a filename input, and you can optionally specify fmt.
[A,map] = imread(___) reads the indexed image in filename into A and reads its associated
colormap into map. Colormap values in the image file are automatically rescaled into the
range [0,1].
Example:
A = imread('ngc6543a.jpg');
image(A)
Output:
Displaying an image in MATLAB refers to the process of visualizing the image matrix stored in MATLAB's
workspace. Once an image is read and stored as a matrix, you can use the imshow function to display it as an
image on your screen.To display image data, use the imshow function. The following example reads an image
into the workspace and then displays the image in a figure window using the imshow function.
Example:
moon = imread("moon.tif");
imshow(moon)
You can also pass imshow the name of a file containing an image.
imshow("moon.tif");
This syntax can be useful for scanning through images. Note, however, that when you use this syntax, imread
does not store the image data in the workspace. If you want to bring the image into the workspace, you must
use the getimage function, which retrieves the image data from the current image object. This example assigns
the image data from moon.tif to the variable moon, if the figure window in which it is displayed is currently
active.
moon = getimage;
Output:
(b) converting color image to gray and black and-white and plotting their histograms
I = im2gray(RGB) converts the specified truecolor image RGB to a grayscale intensity image I. The im2gray
function accepts grayscale images as inputs and returns them unmodified. The im2gray function converts RGB
images to grayscale by eliminating the hue and saturation information while retaining the luminance.
Example:
RGB = imread('example.tif');
imshow(RGB)
Before:
I = im2gray(RGB);
imshow(I)
After:
Plotting histogram:
Finally, we plot the original color image and its grayscale and black-and-white versions, along with their
respective histograms using the subplot and imhist functions.
Code:
color_image = imread('/MATLAB Drive/Screenshot 2024-05-12 120853.png'); % Replace
'path_to_your_image.jpg' with the actual path to your image file
gray_image = rgb2gray(color_image);
threshold = graythresh(gray_image); % Compute a threshold automatically
bw_image = imbinarize(gray_image, threshold);
subplot(3, 1, 1);
imshow(color_image);
title('Color Image');
subplot(3, 1, 2);
imshow(gray_image);
title('Grayscale Image');
xlabel('Pixel Intensity');
ylabel('Frequency');
imhist(gray_image);
subplot(3, 1, 3);
imshow(bw_image);
title('Black-and-White (Binary) Image');
xlabel('Pixel Intensity');
ylabel('Frequency');
imhist(bw_image);
Output:
(c) conversion of image file formats
In MATLAB, you can use the imwrite() function to convert an image from one file format to another. Here's
a simple example:
Code:
% Read the image
image_data = imread('/MATLAB Drive/Screenshot 2024-05-12 120853.png'); % Replace
'input_image.jpg' with the actual path to your input image file
Output:
PNG:
JPG: