0% found this document useful (0 votes)
14 views10 pages

MATLAB Solutions for Computational Physics

The document provides a complete solution set for various MATLAB programming questions related to computational physics. Each question includes a problem statement, MATLAB code, and an explanation of the code's functionality. Topics covered include bacteria growth modeling, numerical integration, solving ordinary differential equations, interpolation, matrix operations, and more.

Uploaded by

mehrankhanm375
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)
14 views10 pages

MATLAB Solutions for Computational Physics

The document provides a complete solution set for various MATLAB programming questions related to computational physics. Each question includes a problem statement, MATLAB code, and an explanation of the code's functionality. Topics covered include bacteria growth modeling, numerical integration, solving ordinary differential equations, interpolation, matrix operations, and more.

Uploaded by

mehrankhanm375
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

Deepseek Chat

Computational physics …
PDF 2.52MB

solve this file all papers those long question in which they ask
to solve the question with MATLAB programing 1st its question
and then answer

Here is a complete solution set for all MATLAB programming


questions found in the file, organized question-by-question, with
MATLAB code and explanations.

Question 1 – Bacteria Growth (from Page 1,


Q2(f))
Problem:
The growth of bacteria is given by N = N0 ekt , where N0 = 1,
​ ​

k = 1.0397, and the population doubles every hour.


Write a MATLAB script to calculate the number of bacteria every
hour for 24 hours.

MATLAB Code:

matlab

% Bacteria growth model


N0 = 1; % initial bacteria
k = 1.0397; % growth constant
hours = 24;

for t = 0:hours
N = N0 * exp(k * t);
fprintf('Hour %2d: Bacteria = %.2f\n', t, N);
end

Explanation:
We loop through each hour, calculate N using the exponential
growth formula, and print the result.

Question 2 – Simpson’s 1/3 Rule Integration


(from Page 1, Q2(c) & Page 2, Q3(b))
Problem:
1
dx
Evaluate ∫0 2+x 2 using Simpson’s 1/3 rule with n
​ ​ = 8. Also,
compute the analytical value and the error.

MATLAB Code:

matlab

% Simpson's 1/3 rule for given integral


f = @(x) 1 ./ (2 + x.^2);
a = 0;
b = 1;
n = 8; % must be even
h = (b - a) / n;

x = a:h:b;
y = f(x);

% Simpson's formula
sum = y(1) + y(end);
for i = 2:2:n
sum = sum + 4 * y(i);
end
for i = 3:2:n-1
sum = sum + 2 * y(i);
end
I_simpson = (h/3) * sum;

% Analytical value
I_exact = (1/sqrt(2)) * atan(1/sqrt(2)); % from ∫dx/(2+x²) = (1/√
2) arctan(x/√2)
error = abs(I_exact - I_simpson);

fprintf('Simpson’s result: %.6f\n', I_simpson);


fprintf('Exact result: %.6f\n', I_exact);
fprintf('Error: %.6f\n', error);

Explanation:
We define the function, create an array of x values, apply
Simpson’s rule formula, and compare with the exact integral.

Question 3 – Euler’s Method for ODE (from Page


1, Q2(a))
Problem:
dy
Solve dx ​ = x + y , y(0) = 1, on [0, 0.5] using Euler’s method with
h = 0.1.
Exact solution: y = 2ex − (x + 1). Estimate the error.

MATLAB Code:

matlab

% Euler's method for dy/dx = x + y


f = @(x, y) x + y;
y0 = 1;
x0 = 0;
x_end = 0.5;
h = 0.1;

x = x0:h:x_end;
y = zeros(size(x));
y(1) = y0;

% Euler iteration
for i = 1:length(x)-1
y(i+1) = y(i) + h * f(x(i), y(i));
end
% Exact solution
y_exact = 2*exp(x) - (x + 1);

% Display results
fprintf(' x Euler y Exact y Error\n');
for i = 1:length(x)
fprintf('%.1f %.4f %.4f %.6f\n', x(i), y(i), y_exact
(i), abs(y(i)-y_exact(i)));
end

Explanation:
We implement Euler’s formula yn+1 ​ = yn + hf (xn , yn ) and
​ ​ ​

compare with the exact solution.

Question 4 – Newton’s Forward Difference


Interpolation (from Page 1, Q2(f))
Problem:
Given data points for f (x), compute the difference table and
interpolate f (0.125) using Newton’s forward difference formula.

MATLAB Code:

matlab

% Newton's forward difference interpolation


x = [0.00, 0.25, 0.50, 0.75, 1.00];
y = [0.0000, 0.2763, 0.5205, 0.7112, 0.8427];
n = length(x);

% Difference table
diff_table = zeros(n, n);
diff_table(:,1) = y';

for j = 2:n
for i = 1:n-j+1
diff_table(i,j) = diff_table(i+1, j-1) - diff_table(i, j-
1);
end
end

% Interpolate at x_target = 0.125


x_target = 0.125;
h = x(2) - x(1);
u = (x_target - x(1)) / h;

% Newton’s forward formula


result = y(1);
product = 1;
for i = 2:n
product = product * (u - (i-2)) / (i-1);
result = result + product * diff_table(1, i);
end

fprintf('Interpolated f(0.125) = %.6f\n', result);

Explanation:
We build a forward difference table and apply Newton’s forward
interpolation formula.

Question 5 – Matrix Input and Sum (from Page


2, Q6(b))
Problem:
Write a MATLAB program that takes two 3×3 matrices A and B at
runtime, prints them in tabular form, and prints their sum C.

MATLAB Code:

matlab

% Matrix input and sum


A = input('Enter matrix A (3x3) as [row1; row2; row3]: ');
B = input('Enter matrix B (3x3) as [row1; row2; row3]: ');

C = A + B;
fprintf('Matrix A:\n');
disp(A);
fprintf('Matrix B:\n');
disp(B);
fprintf('Sum C = A + B:\n');
disp(C);

Explanation:
We use input to get matrices, compute the sum, and display them.

Question 6 – Bisection Method (from Page 5,


Q6(a))
Problem:
Solve sin(x) − 5x + 2 = 0 using bisection method with x1 = 0.4,

x2 = 0.6, corrected to 4 decimal places.


MATLAB Code:

matlab

% Bisection method for sin(x) - 5x + 2 = 0


f = @(x) sin(x) - 5*x + 2;
a = 0.4;
b = 0.6;
tolerance = 1e-5;
max_iter = 100;

if f(a)*f(b) > 0
error('No root in given interval');
end

for i = 1:max_iter
c = (a + b) / 2;
if f(c) == 0 || (b - a)/2 < tolerance
break;
end
if f(a)*f(c) < 0
b = c;
else
a = c;
end
end

fprintf('Root: %.4f\n', c);

Explanation:
We check for a sign change, then iteratively narrow the interval until
the root is found to desired accuracy.

Question 7 – Vector Element Manipulation (from


Page 5, Q6(b))
Problem:
Given vector V , double elements that are positive and divisible by 3
or 5, and cube elements that are negative but greater than −5.

MATLAB Code:

matlab

V = [5, 17, -3, 8, 0, -7, 12, 15, 20, -6, 6, 4, -7, 16];

for i = 1:length(V)
if V(i) > 0 && (mod(V(i),3)==0 || mod(V(i),5)==0)
V(i) = V(i) * 2;
elseif V(i) < 0 && V(i) > -5
V(i) = V(i)^3;
end
end

disp('Modified vector:');
disp(V);

Explanation:
We loop through the vector, apply conditions, and modify elements
accordingly.
Question 8 – Taylor Series for ex (from Page 9,
Q6(b))
Problem:
Write a MATLAB program to compute ex using Taylor series,
stopping when a term is < 0.0001, but limit iterations to 30.

MATLAB Code:

matlab

x = input('Enter x for e^x: ');


term = 1;
sum = term;
n = 1;

while abs(term) >= 0.0001 && n <= 30


term = term * x / n;
sum = sum + term;
n = n + 1;
end

if n > 30 && abs(term) >= 0.0001


fprintf('More than 30 terms needed.\n');
else
fprintf('e^(%.2f) ≈ %.6f (using %d terms)\n', x, sum, n);
end

Explanation:
We iteratively compute terms until the term is small enough or we
exceed 30 terms.

Question 9 – Creating a Special Matrix (from


Page 7, Q6(a))
Problem:
Create an m × n matrix where:

First row = column numbers

First column = row numbers

Other elements = element above + element to the left

MATLAB Code:

matlab

m = input('Enter m: ');
n = input('Enter n: ');
A = zeros(m, n);

% First row
A(1, :) = 1:n;
% First column
A(:, 1) = 1:m;

% Fill rest
for i = 2:m
for j = 2:n
A(i,j) = A(i-1,j) + A(i,j-1);
end
end

disp('Generated matrix:');
disp(A);

Explanation:
We initialize, set first row and column, then compute remaining
elements.

Let me know if you’d like a single merged script for any of these, or
if you need explanations for C++ versions of any problems.

Common questions

Powered by AI

The MATLAB script calculates the bacterial population using the exponential growth formula N = N0 * exp(k * t), where N0 is the initial population, k is the growth constant, and t is time. The assumption is that the population doubles every hour with a specific growth constant k = 1.0397, reflecting continuous exponential growth .

The MATLAB program iterates through each element of vector V, doubling elements if they're positive and divisible by 3 or 5, and cubing negative elements greater than -5. Without checks, errors may occur if the logic fails (e.g., negative indices, non-integers), leading to runtime errors or crashes. Additional safeguards might include input validation or ensuring divisibility conditions are strictly met .

Euler's Method approximates the solution to the differential equation dy/dx = x + y with y(0) = 1 over [0, 0.5] by using an iterative time-stepping approach with step size h = 0.1. It progresses from an initial value, using the slope at each step to estimate the next value, resulting in a series of approximate solution points. It is then compared with the exact solution y = 2e^(-x)(x + 1) for error analysis .

The program constructs a forward difference table with given x and y values, iteratively computes the differences, and applies Newton’s formula for forward interpolation. Using the differences, it calculates the interpolated value at x = 0.125 by substituting into the incremental formula which iteratively sums terms weighing the target position in its differences' context, resulting in an interpolated function value for f(0.125).

Simpson's 1/3 rule is implemented by defining a function f(x) = 1 / (2 + x^2), computing integral estimates over intervals defined by n = 8 subdivisions with an even distribution. The MATLAB script uses loop structures to compute the weighted sum of function values. The approximation I_simpson is compared to the analytical integral solution I_exact derived analytically as (1/sqrt(2)) * atan(1/sqrt(2)), allowing for error estimation .

The MATLAB script initializes an m×n zero matrix. The first row and column are populated with sequential integers, representing indices. Remaining elements are computed using the sum of the element above and to the left. This recursive filling patterns scaffolds the matrix around known constants, such as indices, reflecting systematic value growth across matrix dimensions .

The bisection method in MATLAB iteratively halves an interval [a, b] based on the sign change of f(x) = sin(x) - 5x + 2 until the root is sufficiently accurate. The challenges include ensuring initial interval contains the root (i.e., function signs at ends differ), and iterating until the interval is smaller than a tolerance (1e-5) or the function at mid-point c is zero. This prevents infinite looping if no root exists within given bounds .

Taylor series provides a finite sum approximation of ex by expanding it into terms like 1 + x + (x^2)/2! + ... until a term is smaller than 0.0001 or 30 terms are computed. The series accounts for incremental precision, while controlling iterations in MATLAB limits computational overhead. This method balances accuracy with program execution time, highlighting an essential consideration in numerical methods .

You might also like