NME LAB Report
NME LAB Report
http://rcet.uet.edu.pk http://uet.edu.pk
Lab Manual
Numerical Method in Engineering
SUBMITTED BY:
ABEER AHMAD
REGISTRATION NO:
2022-IM-102
SUBMITTED TO:
Dr. Majid Hussain
Lab session no 01
Introduction to MATLAB
Introduction
MATLAB is a powerful and versatile laboratory environment commonly used in
scientific research and experimentation. MATLAB, short for "Matrix Laboratory,"
is a popular software platform for numerical computing, data analysis, and
visualization. In this lab manual, we will cover the basics of MATLAB, including
essential commands that you will need to perform various tasks.
Getting Started
Before we dive into the basic commands, let's make sure you have MATLAB
installed and set up on your system. If you haven't already done so, please follow
the installation instructions provided by your instructor or refer to the official
MATLAB documentation.
Once MATLAB is installed, open the application and you should be greeted with a
command-line interface where you can start executing commands.
Basic Commands
MATLAB provides a wide range of commands for various scientific and analytical
tasks. Below is a table of some basic MATLAB commands to get you started:
Command Description
MATLAB windows:
MATLAB provides various windows and interfaces that allow users to interact
with the software efficiently. These windows serve different purposes and
provide distinct functionalities to aid users in their data analysis and algorithm
development tasks. Here are some of the key MATLAB windows:
1. Command Window:
• The Command Window is the primary interface for interacting with
MATLAB. It is a text-based interface where you can enter MATLAB
commands and scripts. When you type and execute commands, the
results are displayed in the Command Window. It's a powerful
environment for quick calculations, data exploration, and running
individual commands.
2. Editor Window:
• The Editor Window is where you can create, edit, and save MATLAB
scripts and functions. It provides features like syntax highlighting,
code suggestions, and debugging tools to make writing and
maintaining MATLAB code more efficient. You can also run sections
of code from the Editor Window.
3. Current Folder:
• The Current Folder window displays the files and directories in your
current working directory. You can navigate through your file system,
manage files, and set your working directory directly from this
window. It helps you keep track of your data and scripts.
4. Workspace:
• The Workspace window shows the list of variables currently in
memory, along with their values. You can inspect, edit, or clear
variables from this window. It's a valuable tool for monitoring and
managing your workspace during data analysis.
5. Command History:
• The Command History window maintains a record of previously
executed commands. You can access and rerun specific commands
from your history, which is especially helpful when you want to reuse
or modify previous instructions without retyping them.
6. Figure Window:
• When you create plots, graphs, or visualizations using MATLAB, they
appear in separate Figure Windows. Each Figure Window is a
dedicated space for graphical output. You can customize and export
plots from these windows.
7. Simulink (optional):
• If you are using MATLAB for modeling and simulating dynamic
systems, you may also have access to the Simulink window. Simulink
is a companion tool for MATLAB that provides a graphical
environment for designing and simulating dynamic systems, including
control systems, signal processing, and more.
8. Live Editor (recent feature):
• The Live Editor combines the capabilities of the Editor and the
Command Window into a single document. It allows you to write
code, add explanations, and create interactive documents with live
scripts. You can execute code cells individually and see the results
immediately.
Format commands:
A table listing some commonly used format commands in MATLAB along with
their descriptions:
Command Description
format short Sets the numeric format to short (default, 4 decimal places).
format long Sets the numeric format to long (16 decimal places).
format bank Sets the numeric format to 2 decimal places with currency symbols.
format short G Sets the numeric format to the most compact representation.
format long G Sets the numeric format to long format with compact exponent.
Command Description
exit or quit Terminate the MATLAB session and exit the program.
Ctrl + D (on Linux/Unix) Exit MATLAB by pressing Ctrl and D keys simultaneously.
Ctrl + Z (on Windows) Exit MATLAB by pressing Ctrl and Z keys simultaneously.
Lab session no 02
Trivial calculations and control screen output with format.
Scalar arithmetic operations:
Scalar operations involve mathematical calculations on individual numbers, as
opposed to array or matrix operations. Here is a table of common scalar
arithmetic operations in MATLAB, along with the corresponding commands:
Addition + a = 5 + 3; a = 8;
Subtraction - b = 7 - 2; b = 5;
Multiplication * c = 4 * 6; c = 24;
Division / d = 9 / 3; d = 3;
Exponentiation ^ or ** e = 2^3; e = 8;
Order of precedence:
In MATLAB, operators and functions have a specific order of precedence, which
determines the sequence in which operations are evaluated in expressions. Here's
a table showing the order of precedence in MATLAB, from highest to lowest
precedence, along with some example commands:
Precedence Level Operator / Function
1 Parentheses ( )
2 Exponentiation ^
3 Negation -
5 Addition +, Subtraction -
10 Colon Operator :
eps is approximately
eps Smallest positive floating-point number. 2.2204e-16.
NaN (with
capital 'N') Not-a-Number in uppercase. 0/0 results in NaN.
Built in functions:
MATLAB provides a wide range of built-in functions that cover various
mathematical, scientific, and engineering domains. Here's a table of some
commonly used built-in functions in MATLAB:
Theory:
Arrays in MATLAB are fundamental data structures that allow you to store and
manipulate sets of numerical data. A vector is a one-dimensional array, while a matrix is
a two-dimensional array.
Commands:
Command Description
row_vector = [1, 2, 3, 4, 5]; Creates a row vector.
col_vector = [6; 7; 8; 9; 10]; Creates a column vector.
matrix = [11, 12, 13; 14, 15, 16; 17, 18, 19]; Creates a matrix.
Theory:
Commands:
Theory:
MATLAB provides various built-in functions for array manipulation, including sum, mean,
maximum, and minimum.
Commands:
Theory:
Special matrices like identity, zeros, ones, random, diagonal, transpose, and inverse
matrices play essential roles in various mathematical and engineering applications.
Commands:
Matrix
Type Command Description
Identity identity_matrix = eye(n); Creates an identity matrix of size n.
Zeros zeros_matrix = zeros(m, n); Creates a matrix of zeros with size m x n.
Ones ones_matrix = ones(m, n); Creates a matrix of ones with size m x n.
Creates a matrix of random values with
Random random_matrix = rand(m, n); size m x n.
diagonal_matrix = Creates a diagonal matrix with specified
Diagonal diag(diagonal_elements); diagonal elements.
transposed_matrix =
Transpose transpose(matrix); Computes the transpose of a matrix.
Inverse inverse_matrix = inv(matrix); Computes the inverse of a square matrix.
Lab session no 04
Theory:
Simple plots are fundamental for visualizing data in MATLAB. The plot function is
commonly used to create 2D line plots. Understanding the basic components of a plot,
such as axes, labels, and titles, is essential.
Commands:
Command Description
x = linspace(0, 2*pi, 100); Generates a vector of 100 points from 0 to 2π.
y = sin(x); Computes the sine values for each point in the vector.
plot(x, y); Creates a simple 2D plot.
xlabel('X-axis Label'); Adds a label to the X-axis.
ylabel('Y-axis Label'); Adds a label to the Y-axis.
title('Simple Plot'); Adds a title to the plot.
grid on; Displays the grid on the plot.
Theory:
Logarithmic scales are useful when dealing with data that spans several orders of
magnitude. In MATLAB, you can use semilogx, semilogy, or loglog to create plots with
logarithmic scales.
Commands:
Command Description
x = linspace(0.1, 10, 100); Generates a vector from 0.1 to 10.
y = log(x); Computes the natural logarithm of each element in x.
semilogy(x, y); Creates a plot with a logarithmic Y-axis.
xlabel('X-axis Label'); Adds a label to the X-axis.
Command Description
ylabel('Y-axis Label (log scale)'); Adds a label to the Y-axis.
title('Logarithmic Scale Plot'); Adds a title to the plot.
grid on; Displays the grid on the plot.
Theory:
Basic 2D plots include scatter plots, bar plots, and histograms. These plots are useful for
visualizing relationships between variables and distributions of data.
Commands:
Command Description
Generates a vector of 100 random numbers from a standard normal
x = randn(100, 1); distribution.
y = randn(100, 1); Generates another vector of 100 random numbers.
scatter(x, y); Creates a scatter plot.
xlabel('X-axis
Label'); Adds a label to the X-axis.
ylabel('Y-axis
Label'); Adds a label to the Y-axis.
title('Scatter
Plot'); Adds a title to the plot.
grid on; Displays the grid on the plot.
This comprehensive manual covers the creation of simple graphs, including basic 2D
plots and logarithmic scales, in MATLAB. The provided commands are illustrative and
can be adjusted according to specific data and requirements.
Lab session no 05
Theory:
Commands:
II. M-Files
Theory:
M-files in MATLAB are script files or functions stored in separate files. They enhance
code organization and reusability.
Commands:
Command Description
edit myScript.m; Opens the MATLAB Editor for creating a script file.
edit myFunction.m; Opens the MATLAB Editor for creating a function file.
Theory:
Controlling input and output in MATLAB involves reading from and writing to files,
enabling interaction with external data.
Commands:
Command Description
fid = fopen('myFile.txt', 'r'); Opens a file for reading and returns a file identifier.
Reads numeric data from the file using the specified
data = fscanf(fid, '%f'); format.
fclose(fid); Closes the file.
fid = fopen('output.txt', 'w'); Opens a file for writing.
fprintf(fid, '%s\n', 'Hello,
World!'); Writes a string to the file.
fclose(fid); Closes the file.
Theory:
Commands:
Command Description
result = myFunction(@sin, Calls a custom function ( myFunction) with the sine function as an
x); argument.
result = myFunction(@exp, Calls the same function with the exponential function as an
x); argument.
This manual covers elementary mathematical functions, creating and using M-files,
controlling input and output with files, and passing functions to M-files. Adjust the
commands based on your specific use case and data.
Lab session no 06
Programming in MATLAB
I. Conditional Statements
Theory:
Conditional statements in MATLAB allow you to execute different code blocks based on
specified conditions. The if, else, and elseif statements are commonly used.
Commands:
Command Description
if condition Executes code if the condition is true.
% Code to execute if the condition is
true
Theory:
Relational operators in MATLAB are used to compare values. These include equality (==),
inequality (~=, !=), greater than (>), less than (<), greater than or equal to (>=), and less
than or equal to (<=).
Commands:
Command Description
result = (a == b); Checks if a is equal to b.
result = (a ~= b); Checks if a is not equal to b.
result = (a > b); Checks if a is greater than b.
result = (a < b); Checks if a is less than b.
result = (a >= b); Checks if a is greater than or equal to b.
result = (a <= b); Checks if a is less than or equal to b.
III. Loops
Theory:
Loops in MATLAB enable you to repeatedly execute a block of code. Common loop
structures include for and while loops.
Commands:
Command Description
for i = start:step:end Executes code for each iteration of the loop.
% Code to execute in each iteration
Commands:
Command Description
sum_even = 0; Initializes a variable to store the sum of even numbers.
for i = 1:10 Loops through numbers 1 to 10.
Command Description
if mod(i, 2) == 0 Checks if the number is even.
sum_even = sum_even + i; Adds the even number to the sum.
end Ends the if statement.
end Ends the for loop.
Lab session no 07
Roots of Equations
I. Polynomial Roots
Theory:
Polynomial roots are the values of the variable that make the polynomial equation equal
to zero. MATLAB provides functions to find these roots efficiently.
Commands:
Command Description
coefficients = [a, b, c, ...]; Define the coefficients of the polynomial.
roots_of_polynomial = roots(coefficients); Computes the roots of the polynomial.
Theory:
Nonlinear algebraic equations are equations where the unknowns appear as variables
raised to powers or in other nonlinear forms. These equations are solved using iterative
methods.
Commands:
Command Description
equation = @(x) x^2 - 4; Define the nonlinear algebraic equation.
initial_guess = 2; Provide an initial guess for the root.
root = fzero(equation, Computes the root of the equation using the fzero
initial_guess); function.
Theory:
The Bisection Method is an iterative numerical technique for finding the root of a real-
valued function. It requires an interval where the function changes sign.
Commands:
Command Description
Define the function for which the root is
fun = @(x) x^2 - 4; to be found.
Define the interval [a, b] where the root
a = 1; b = 3; exists.
tolerance = 1e-6; Set the tolerance level for convergence.
[root, iterations] = bisection_method(fun, a, b,
tolerance); Implement the Bisection Method.
Theory:
The Newton-Raphson Method is an iterative numerical technique for finding the root of
a real-valued function. It converges quickly if the initial guess is close to the actual root.
Commands:
Command Description
Define the function for which
fun = @(x) x^2 - 4; the root is to be found.
Define the derivative of the
derivative = @(x) 2*x; function.
Provide an initial guess for the
initial_guess = 2; root.
Set the tolerance level for
tolerance = 1e-6; convergence.
[root, iterations] = newton_raphson_method(fun, Implement the Newton-
derivative, initial_guess, tolerance); Raphson Method.
Lab session no 08
Theory:
Linear algebraic equations represent a system of linear equations, where each equation
is a linear combination of variables. Solving such a system involves finding values for the
variables that satisfy all equations simultaneously.
Commands:
Command Description
A = [a11, a12, ...; a21, a22, ...; ...]; Define the coefficient matrix A.
b = [b1; b2; ...]; Define the right-hand side vector b.
x = A \ b; Solve the linear system using left-division.
Theory:
Commands:
Command Description
A = [a11, a12, ...; a21, a22, ...; ...]; Define the matrix A.
[L, U, P] = lu(A); LU decomposition with partial pivoting.
[Q, R] = qr(A); QR decomposition.
eigenvalues = eig(A); Compute eigenvalues of A.
Theory:
The left-division method (\) in MATLAB is used to solve a system of linear equations by
finding the least squares solution.
Commands:
Command Description
A = [a11, a12, ...; a21, a22, ...; ...]; Define the coefficient matrix A.
b = [b1; b2; ...]; Define the right-hand side vector b.
x = A \ b; Solve the linear system using left-division.
Theory:
The matrix inverse method involves computing the inverse of the coefficient matrix and
then multiplying it by the right-hand side vector to find the solution.
Commands:
Command Description
A = [a11, a12, ...; a21, a22, ...;
...]; Define the coefficient matrix A.
b = [b1; b2; ...]; Define the right-hand side vector b.
A_inv = inv(A); Compute the inverse of A.
Solve the linear system using the matrix inverse
x = A_inv * b; method.
Theory:
Commands:
Command Description
augmented_matrix = [A, b]; Create the augmented matrix.
rref_matrix = rref(augmented_matrix); Compute the reduced row echelon form.
Command Description
solution_vector = rref_matrix(:, end); Extract the solution vector from the last column.
Theory:
The Gauss-Seidel iteration method is an iterative approach for solving linear systems,
particularly useful for large sparse matrices.
Commands:
Command Description
A = [a11, a12, ...; a21, a22, ...; ...]; Define the coefficient matrix A.
b = [b1; b2; ...]; Define the right-hand side vector b.
Provide an initial guess for the
x_initial = [x1_initial; x2_initial; ...]; solution.
x = gauss_seidel(A, b, x_initial, tolerance, Implement the Gauss-Seidel iteration
max_iterations); method.
Lab session no 09
Interpolation
I. Interpolation
Theory:
Commands:
Command Description
x = [x1, x2, ...]; Define the x-coordinates of known data points.
Define the corresponding y-coordinates of
y = [y1, y2, ...]; known data points.
Choose the interpolation method ('linear',
interp_method = 'method'; 'spline', 'pchip', etc.).
interp_values = interp1(x, y, x_values,
interp_method); Perform interpolation at specified x-values.
Theory:
Commands:
Command Description
Define the x-coordinates of known data
x = [x1, x2, ...]; points.
Define the corresponding y-coordinates of
y = [y1, y2, ...]; known data points.
Command Description
lagrange_polynomial = Compute the Lagrange interpolating
lagrange_interpolation(x, y, x_values); polynomial.
Lab session no 10
Theory:
Commands:
Command Description
fun = @(x) ...; Define the function to be integrated.
a = ...; Define the lower limit of integration.
b = ...; Define the upper limit of integration.
Define the number of subintervals for the
n = ...; Trapezoidal Rule.
integral_value = trapezoidal_rule(fun, a, Perform numerical integration using the
b, n); Trapezoidal Rule.
Theory:
Commands:
Command Description
Define the ODE as a
ode_function = @(t, y) ...; function of t and y.
initial_condition = ...; Define the initial condition.
Define the time span for
t_span = [t_initial, t_final]; the solution.
Command Description
Define the step size for the
step_size = ...; numerical solution.
Implement the Fourth-
[t_values, y_values] = runge_kutta_4th_order(ode_function, Order Runge-Kutta
t_span, initial_condition, step_size); method.
Define the time points for
t_values = t_initial:step_size:t_final; Euler's method.
y_values = euler_method(ode_function, initial_condition,
t_values, step_size); Implement Euler's method.