0% found this document useful (0 votes)
5 views25 pages

Introduction to MATLAB Programming

Uploaded by

kalllmerri
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)
5 views25 pages

Introduction to MATLAB Programming

Uploaded by

kalllmerri
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

What is MATLAB?

❖MATLAB stands for MATrix LABoratory.


It is a computer program and programming language used by engineers, scientists, and students
to:
• Do calculations
• Plot graphs
• Analyze data
• Simulate systems
• Write algorithms
• Think of it as a powerful calculator that can handle both simple math and complex engineering
problems.
Where is MATLAB used ?
1. Mathematics-Solving equation, Plotting function
2. Engineering-Designing Control System, Analyzing Circuit.
3. AI and Robotics-Image Processing, Control Algorithm
4. Science-Modeling Experiment and Data
MATLAB Environment (Main Parts)
When you open MATLAB, you’ll see these key areas:
➢ Command Window – where you type and run commands
➢ Workspace – shows variables you have created
➢ Current Folder – shows files in your working directory
➢ Editor – where you write and save your scripts (programs)
➢ Figure Window – where MATLAB shows your plots and graphs
Basic Command
Action Command Meaning
Assign a number a = 5; Creates a variable a and stores 5
Display result a Shows the value of a
Create vector v = [1 2 3 4]; Row vector with 4 elements
Create matrix A = [1 2; 3 4]; 2×2 matrix
Add matrices C = A + B; Element-by-element addition
Multiply matrices C = A * B; Standard matrix multiplication
Plot graph plot(x, y) Draws 2D line plot
Removes all variables from
Clear variables clear
workspace
Shows how to use the plot
Help help plot
command
Example: Simple Math
a = 10;
b = 5;
sum = a + b;
product = a * b;
disp(sum)
disp(product)
Example 2: Plotting Graph
x = 0:0.1:10; % Numbers from 0 to 10 in steps of 0.1
y = sin(x); % Sine of each x value
plot(x, y)
xlabel('x')
ylabel('sin(x)')
title('Sine Wave')
grid on
Useful MATLAB Commands
Command Description
clc Clears command window
clear Removes variables
close all Closes all plots
disp() Displays text or variables
fprintf() Formatted output printing
hold on Keeps multiple plots on same figure

What Are Conditions?


A condition checks whether something is true or false, and MATLAB runs code accordingly.
The main structure is:
if condition
statements
elseif another_condition
statements
else
statements
end
If-else-if condition What Are Loops?
x = 0; A loop repeats a set of instructions multiple times — until a condition is met.
if x > 0 There are two main types:
➤ A. for loop: Used when you know how many times you want to repeat
disp('Positive');
something.
elseif x < 0 Structure: for variable = start : step : end
disp('Negative'); statements
end
else
Example: for i = 0:2:10
disp('Zero'); disp(i)
end end
B. While Loop
Used when you don’t know how many times to repeat — it continues until a
condition becomes false.
Example: x = 1;
while x^2 < 50
disp(x)
x = x + 1;
end
Default Color format

Color Meaning Example

Green Comment % this is a comment

Blue Keyword / command if, for, while, end, function

Purple Text (string) 'Hello'

Orange Number 3.14, 10, -5

Black Variable or general code a = 5; b = a + 2;

Red Error or unclosed statement Missing end or '

Light Blue Built-in function plot, sin, cos, sqrt


BISECTION METHOD
% Step 1 — Clear and define things
clc; clear; % Clear the command window and remove all previous variables
% Step 2 — Define function, starting interval and accuracy
f = @(x) x.^3 - x - 2; % Define the function f(x). You can change the function here.
a = 1; % Set the lower limit of the interval where the root is suspected
b = 2; % Set the upper limit of the interval
tol = 1e-6; % Set the tolerance for stopping the iteration (accuracy of root)
% Step 3 — Check if a root exists in [a,b]
if f(a)*f(b) > 0 % Check if there is a sign change between a and b
error('No sign change detected. Choose a different interval.'); % Stop if no root is guaranteed
end
% Step 4 — Start the loop (iteration), compute the mid point, Check if midpoint is good enough
for i = 1:50 % Start a loop with a maximum of 50 iterations
c = (a + b)/2; % Compute the midpoint of the interval
if abs(f(c)) < tol % Check if the function value at midpoint is within the tolerance
break; % Stop the loop if the root is found
elseif f(a)*f(c) < 0 % If sign change occurs between a and c
b = c; % Update the right endpoint to the midpoint
else % If sign change occurs between c and b
a = c; % Update the left endpoint to the midpoint
end
end
% Step 5: Display result
fprintf('Root ≈ %.6f after %d iterations\n', c, i); % Display the root and number of iterations

x = linspace(a-1, b+1, 200); % Generate 200 points around the interval for plotting
y = f(x); % Compute function values for each x
% Step 6: Display the Graph
figure; % Open a new figure window
plot(x, y, 'b', 'LineWidth', 1.5); hold on; % Plot the function curve in blue
plot(c, f(c), 'ro', 'MarkerFaceColor', 'r'); % Mark the approximate root as a red circle
yline(0, '--k'); % Draw a dashed black line for the x-axis
grid on; % Turn on grid
xlabel('x'); % Label x-axis
ylabel('f(x)'); % Label y-axis
title('Bisection Method Visualization'); % Set the title of the plot
legend('f(x)', 'Approximate Root'); % Add a legend to indicate the function and root
Result approx. 1.521380 after 22 iteration
BISECTION USING TABLE AND ARE
clc; clear; % Clear the command window and remove all previous variables

f = @(x) x.^3 - x - 2; % Define the function f(x). Use .^ for element-wise power so it works on vectors (for
plotting)

a = 1; % Set the lower limit of the interval where the root is suspected
b = 2; % Set the upper limit of the interval
tol = 1e-6; % Set the tolerance for stopping iteration (desired accuracy)

if f(a)*f(b) > 0 % Check if the function changes sign in [a,b]; bisection requires a sign change
error('No sign change detected. Choose a different interval.'); % Stop execution if no root is guaranteed
end
c_old = a; % Initialize previous midpoint for calculating Approximate Relative Error (ARE)

% Print table header for iteration results


fprintf('Iter\t a\t\t b\t\t c\t\t f(c)\t\t Approx. Rel. Error\n');
fprintf('----------------------------------------------------------------------------------\n');
for i = 1:50 % Maximum of 50 iterations
c = (a + b)/2; % Compute the midpoint of the interval [a,b]
fc = f(c); % Compute the function value at the midpoint
if i == 1 % For the first iteration
ARE = NaN; % No previous midpoint exists, so ARE is not defined
else
ARE = abs((c - c_old)/c) * 100; % Compute approximate relative error in percentage
end
% Print iteration details in a table format
fprintf('%2d\t %10.6f\t %10.6f\t %10.6f\t %12.6e\t %12.6f%%\n', i, a, b, c, fc, ARE);
if abs(fc) < tol % Check if the function value is close enough to zero
break; % Stop the loop if root is found
elseif f(a)*fc < 0 % Check if the root lies in [a,c]
b = c; % Update the right endpoint to the midpoint
else % Otherwise, the root lies in [c,b]
a = c; % Update the left endpoint to the midpoint
end
c_old = c; % Update previous midpoint for next iteration
end
% Display the final approximate root and total number of iterations
fprintf('\nApproximate Root = %.6f after %d iterations\n', c, i);
% Optional: plot function and root
x = linspace(a-1, b+1, 200); % Generate 200 x-values around the interval for plotting
y = f(x); % Compute function values for all x
figure; % Open a new figure window
plot(x, y, 'b', 'LineWidth', 1.5); hold on; % Plot the function curve in blue
plot(c, f(c), 'ro', 'MarkerFaceColor', 'r'); % Mark the approximate root as a red dot
yline(0, '--k'); % Draw a dashed black line for the x-axis
grid on; % Turn on grid
xlabel('x'); % Label the x-axis
ylabel('f(x)'); % Label the y-axis
title('Bisection Method with Approximate Relative Error'); % Title of the plot
legend('f(x)', 'Approximate Root'); % Add legend for the curve and root
Components explained:

Component Meaning
Iter Column header for iteration number
Tab character → moves the cursor to the next column for
\t
spacing
a Column header for left interval value
\t\t Two tabs → extra spacing for alignment
b Column header for right interval value
c Column header for midpoint value
f(c) Column header for function value at midpoint
Approx. Rel. Error Column header for approximate relative error (ARE)
New line → moves the cursor to the next line so the table
\n
body can be printed
False Position Method
clc; clear; % Clear command window and variables
% Define the function
f = @(x) x.^3 - x - 2;
% Define interval and tolerance
a = 1;
b = 2;
tol = 1e-6;
% Check if root exists in [a,b]
if f(a)*f(b) > 0
error('No root in this interval. Choose a different interval.');
end
c_old = a; % Initial placeholder for ARE
% Print table header
fprintf('Iter\t a\t\t b\t\t c\t\t f(c)\t\t ARE(%%)\n');
fprintf('-----------------------------------------------------------------------\n');
% Maximum 50 iterations
for i = 1:50
% False Position formula
c = b - (f(b)*(b-a))/(f(b)-f(a));
fc = f(c); % Function value at c
% Approximate Relative Error
if i == 1
ARE = NaN; % First iteration has no previous midpoint
else
ARE = abs((c - c_old)/c) * 100;
end
% Print iteration data in aligned table
fprintf('%2d\t %10.6f\t %10.6f\t %10.6f\t %12.6e\t %10.6f\n', i, a, b, c, fc, ARE);
% Update interval based on sign
if abs(fc) < tol
break; % Root found
elseif f(a)*fc < 0
b = c; % Root in left half
else
a = c; % Root in right half
end
c_old = c; % Update previous root for next ARE
end
% Display final approximate root
fprintf('\nApproximate Root = %.6f after %d iterations\n', c, i);
%% ---------------------- Plot the function and root -----------------------
x = linspace(a-0.5, b+0.5, 200); % Generate points around the interval
y = f(x);
figure; % Open a new figure window
plot(x, y, 'b-', 'LineWidth', 1.5); hold on; % Plot function curve
plot(c, f(c), 'ro', 'MarkerFaceColor', 'r'); % Mark approximate root with a red dot
yline(0, '--k'); % Draw horizontal line at y=0
xlabel('x'); ylabel('f(x)'); % Label axes
title('False Position Method: Function and Root'); % Add title
grid on; % Turn on grid
legend('f(x)', 'Approximate Root'); % Add legend
NEWTON-RAPHSON METHOD CONCEPT
• Finds root of 𝑓 𝑥 = 0 using derivative information.
• Formula for iteration:
𝑓 𝑥𝑛
• 𝑥𝑛+1 = 𝑥𝑛 − ′
𝑓 𝑥𝑛
• Steps:
• Choose initial guess 𝑥0 .
• Compute 𝑥1 = 𝑥0 − 𝑓 𝑥0 /𝑓 ′ 𝑥0 .
• Repeat until convergence (e.g., ∣ 𝑥𝑛+1 − 𝑥𝑛 ∣ or ARE < tolerance).
• Faster convergence than Bisection or False Position if derivative is available.
NUETON RAPSON METHOD
clc; clear;
% Define the function and its derivative
f = @(x) x.^3 - x - 2;
df = @(x) 3*x.^2 - 1; % Derivative of f(x)
x0 = 1.5; % Initial guess
tol = 1e-6; % Tolerance
maxIter = 50; % Maximum iterations
x_old = x0; % Initialize previous value for ARE
% Print header
fprintf('Iter\t x\t\t f(x)\t\t ARE(%%)\n');
fprintf('----------------------------------------------\n');
for i = 1:maxIter
fx = f(x_old);
dfx = df(x_old);
% Newton-Raphson formula
x_new = x_old - fx/dfx;
% Approximate Relative Error
if i == 1
ARE = NaN; % First iteration has no previous
else
ARE = abs((x_new - x_old)/x_new) * 100;
end
% Print iteration data
fprintf('%2d\t %10.6f\t %12.6e\t %10.6f\n', i, x_new, f(x_new), ARE);
% Check convergence
if abs(f(x_new)) < tol
break;
end
x_old = x_new; % Update for next iteration
end
fprintf('\nApproximate Root = %.6f after %d iterations\n', x_new, i);

%% ---------------------- Plot the function and root -----------------------


x = linspace(x_new-1, x_new+1, 200); % Plot around the root
y = f(x);

figure;
plot(x, y, 'b-', 'LineWidth', 1.5); hold on; % Function curve
plot(x_new, f(x_new), 'ro', 'MarkerFaceColor', 'r'); % Approximate root
yline(0, '--k'); % Horizontal line y=0
xlabel('x'); ylabel('f(x)');
title('Newton-Raphson Method: Function and Root');
grid on;
legend('f(x)', 'Approximate Root');
SECANT METHOD CONCEPT
• Secant Method approximates the derivative numerically instead of
requiring it explicitly.
• Formula for iteration:
𝑥𝑛 −𝑥𝑛−1
• 𝑥𝑛+1 = 𝑥𝑛 − 𝑓 𝑥𝑛
𝑓 𝑥𝑛 −𝑓 𝑥𝑛−1
• Steps:
• Choose two initial guesses 𝑥0 and 𝑥1 .
• Compute next approximation using the formula above.
• Repeat until convergence (∣ 𝑥𝑛+1 − 𝑥𝑛 ∣< tolerance or ∣ 𝑓 𝑥𝑛+1 ∣
< tolerance)or ARE <Tolerance.
• Faster than Bisection and False Position, doesn’t require derivative,
but slower than Newton-Raphson.
SECANT METHOD
clc; clear;
% Define the function
f = @(x) x.^3 - x - 2;

% Initial guesses
x0 = 1;
x1 = 2;

tol = 1e-6; % Tolerance


maxIter = 50; % Maximum iterations

% Print header
fprintf('Iter\t x_prev\t x_curr\t f(x_curr)\t ARE(%%)\n');
fprintf('---------------------------------------------------------------\n');
for i = 1:maxIter
% Secant formula
x_new = x1 - f(x1)*(x1-x0)/(f(x1)-f(x0));
fx_new = f(x_new);
% Approximate Relative Error
if i == 1
ARE = NaN; % First iteration has no previous
else
ARE = abs((x_new - x1)/x_new) * 100;
end
% Print iteration data
fprintf('%2d\t %10.6f\t %10.6f\t %12.6e\t %10.6f\n', i, x0, x1, fx_new, ARE);
% Check convergence
if abs(fx_new) < tol
break;
end
% Update for next iteration
x0 = x1;
x1 = x_new;
end
fprintf('\nApproximate Root = %.6f after %d iterations\n', x_new, i);

%% ---------------------- Plot the function and root -----------------------


x = linspace(x_new-1, x_new+1, 200); % Plot around the root
y = f(x);

figure;
plot(x, y, 'b-', 'LineWidth', 1.5); hold on; % Function curve
plot(x_new, f(x_new), 'ro', 'MarkerFaceColor', 'r'); % Approximate root
yline(0, '--k'); % Horizontal line y=0
xlabel('x'); ylabel('f(x)');
title('Secant Method: Function and Root');
grid on;
legend('f(x)', 'Approximate Root');

You might also like