0% found this document useful (0 votes)
18 views17 pages

MATLAB Solutions for Programming Tasks

The document provides MATLAB solutions for a series of programming questions, ranging from basic tasks like printing text and plotting graphs to more complex operations such as numerical integration, solving equations, and matrix manipulations. Each question includes a brief description followed by the corresponding MATLAB code. The solutions cover a variety of mathematical and computational concepts, demonstrating the versatility of MATLAB for solving engineering and mathematical problems.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views17 pages

MATLAB Solutions for Programming Tasks

The document provides MATLAB solutions for a series of programming questions, ranging from basic tasks like printing text and plotting graphs to more complex operations such as numerical integration, solving equations, and matrix manipulations. Each question includes a brief description followed by the corresponding MATLAB code. The solutions cover a variety of mathematical and computational concepts, demonstrating the versatility of MATLAB for solving engineering and mathematical problems.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

MATLAB Solutions for Questions 1 to 40

Q1: Print "Hello World"


disp('Hello World');
Q2: Plot the graph of y = sin(x)
x = linspace(0, 2*pi, 100);
y = sin(x);
plot(x, y);
xlabel('x'); ylabel('sin(x)');
title('Graph of y = sin(x)');
grid on;
Q3: Arithmetic Operations on Two Numbers
a = input('Enter first number: ');
b = input('Enter second number: ');
if b == 0
disp('Second number cannot be zero for division.');
else
fprintf('Addition: %f\n', a + b);
fprintf('Subtraction: %f\n', a - b);
fprintf('Multiplication: %f\n', a * b);
fprintf('Division: %f\n', a / b);
end
Q4: Calculate Average and Standard Deviation of an Array
arr = input('Enter an array: ');
avg = mean(arr);
std_dev = std(arr);
fprintf('Average: %f\n', avg);
fprintf('Standard Deviation: %f\n', std_dev);
Q5: Convert Temperature from Celsius to Fahrenheit
C = input('Enter temperature in Celsius: ');
F = (C * 9/5) + 32;
fprintf('Temperature in Fahrenheit: %f\n', F);
Q6: Compute Factorial of a Number
n = input('Enter a non-negative number: ');
if n < 0
disp('Please enter a non-negative number.');
else
fact = prod(1:n);
fprintf('%d! = %d\n', n, fact);
end
Q7: Find Maximum Among Three Numbers
a = input('Enter first number: ');
b = input('Enter second number: ');
c = input('Enter third number: ');
max_num = max([a, b, c]);
fprintf('Maximum number is: %f\n', max_num);
Q8: Find Minimum Among Three Numbers
a = input('Enter first number: ');
b = input('Enter second number: ');
c = input('Enter third number: ');
min_num = min([a, b, c]);
fprintf('Minimum number is: %f\n', min_num);
Q9: Generate First 10 Fibonacci Numbers
n = 10;
fib = zeros(1, n);
fib(1) = 0;
fib(2) = 1;
for i = 3:n
fib(i) = fib(i-1) + fib(i-2);
end
disp('First 10 Fibonacci numbers:');
disp(fib);
Q10: Sum of First n Odd Numbers
n = input('Enter a number: ');
sum_odd = n^2;
fprintf('Sum of first %d odd numbers is: %d\n', n, sum_odd);
Q11: Check Leap Year
year = input('Enter a year: ');
if mod(year, 400) == 0 || (mod(year, 4) == 0 && mod(year, 100) ~= 0)
disp('Leap year');
else
disp('Not a leap year');
end
Q12: Check Prime Number
num = input('Enter a number: ');
if isprime(num)
disp('The number is prime.');
else
disp('The number is not prime.');
end
Q13: Sum of Series 1 + 1/2! + ... + 1/100!
sum_series = sum(arrayfun(@(x) 1/factorial(x), 1:100));
fprintf('Sum of the series: %f\n', sum_series);
Q14: Sum of Geometric Series
sum_series = 1 / (1 - 0.5);
fprintf('Sum of the series: %f\n', sum_series);
Q15: Numerical Integration using Trapezoidal Rule
f = @(x) exp(-x.^2);
a = 0; b = 1; n = 100;
x = linspace(a, b, n+1);
y = f(x);
trapz_result = trapz(x, y);
fprintf('Integral using Trapezoidal Rule: %f\n', trapz_result);
Q16: Find Root using Bisection Method
f = @(x) x^3 - x - 1;
a = 1; b = 2; tol = 1e-6;
while (b - a) / 2 > tol
c = (a + b) / 2;
if f(c) == 0
break;
elseif f(a) * f(c) < 0
b = c;
else
a = c;
end
end
fprintf('Root using Bisection Method: %f\n', c);
MATLAB Solutions for Questions 17 to 40

Q17: Solve x - 2 cos(x) = 0 using Regula-Falsi Method


f = @(x) x - 2 * cos(x);
a = 0; b = 1; tol = 1e-6;
while abs(f(b) - f(a)) > tol
c = (a * f(b) - b * f(a)) / (f(b) - f(a));
if f(c) == 0
break;
elseif f(a) * f(c) < 0
b = c;
else
a = c;
end
end
fprintf('Root using Regula-Falsi Method: %f\n', c);
Q18: Find the Square Root of a Number
N = input('Enter a number: ');
sqrt_N = sqrt(N);
fprintf('Square root of %f is %f\n', N, sqrt_N);
Q19: Solve x e^x - 2 = 0 using Newton-Raphson Method
f = @(x) x * exp(x) - 2;
df = @(x) exp(x) * (x + 1);
x0 = 0.5; tol = 1e-6;
while true
x1 = x0 - f(x0) / df(x0);
if abs(x1 - x0) < tol
break;
end
x0 = x1;
end
fprintf('Root using Newton-Raphson Method: %f\n', x1);
Q20: Bubble Sort Algorithm
arr = input('Enter an array: ');
n = length(arr);
for i = 1:n-1
for j = 1:n-i
if arr(j) > arr(j+1)
temp = arr(j);
arr(j) = arr(j+1);
arr(j+1) = temp;
end
end
end
disp('Sorted array: ');
disp(arr);

21- Matrix Operations (Addition, Subtraction, Multiplication)


A = input('Enter first matrix: ');
B = input('Enter second matrix: ');

fprintf('Matrix Addition:\n');
disp(A + B);

fprintf('Matrix Subtraction:\n');
disp(A - B);
fprintf('Matrix Multiplication:\n');
disp(A * B);

22-Newton-Forward Interpolation

x = input('Enter x values: ');


y = input('Enter y values: ');
xp = input('Enter x for which you need y: ');
n = length(x);

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
y_p = y(1);
u = (xp - x(1)) / (x(2) - x(1));
prod_u = 1; fact = 1;
for j = 2:n
prod_u = prod_u * (u - (j - 2));
fact = fact * (j - 1);
y_p = y_p + (prod_u / fact) * diff_table(1, j);
end
fprintf('Interpolated value of y at x = %f is %f\n', xp, y_p);
Q23: Newton-Backward Interpolation
x = input('Enter x values: ');
y = input('Enter y values: ');
xp = input('Enter x for which you need y: ');
n = length(x);

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
y_p = y(n);
u = (xp - x(n)) / (x(2) - x(1));
prod_u = 1; fact = 1;
for j = 2:n
prod_u = prod_u * (u + (j - 2));
fact = fact * (j - 1);
y_p = y_p + (prod_u / fact) * diff_table(n - j + 1, j);
end
fprintf('Interpolated value of y at x = %f is %f\n', xp, y_p);

Q24: Lagrange’s Interpolation


x = input('Enter x values: ');
y = input('Enter y values: ');
xp = input('Enter x for which you need y: ');
n = length(x);
y_p = 0;
for i = 1:n
term = y(i);
for j = 1:n
if i ~= j
term = term * (xp - x(j)) / (x(i) - x(j));
end
end
y_p = y_p + term;
end
fprintf('Interpolated value of y at x = %f is %f\n', xp, y_p);

Q25: Solve dy/dx = x^2 + y^2, y(0) = 1 using Euler’s Method


f = @(x, y) x^2 + y^2;
x0 = 0; y0 = 1;
h = 0.1; xn = 1;
n = (xn - x0) / h;
for i = 1:n
y1 = y0 + h * f(x0, y0);
x0 = x0 + h;
y0 = y1;
end
fprintf('Solution at x = %f is y = %f\n', x0, y0);

Q26: Solve using Runge-Kutta 2nd Order Method


f = @(x, y) x^2 + y^2;
x0 = 0; y0 = 1;
h = 0.1; xn = 1;
n = (xn - x0) / h;
for i = 1:n
k1 = h * f(x0, y0);
k2 = h * f(x0 + h, y0 + k1);
y0 = y0 + 0.5 * (k1 + k2);
x0 = x0 + h;
end
fprintf('Solution at x = %f is y = %f\n', x0, y0);

Q27: Solve using Runge-Kutta 4th Order Method


f = @(x, y) x^2 + y^2;
x0 = 0; y0 = 1;
h = 0.1; xn = 1;
n = (xn - x0) / h;
for i = 1:n
k1 = h * f(x0, y0);
k2 = h * f(x0 + h/2, y0 + k1/2);
k3 = h * f(x0 + h/2, y0 + k2/2);
k4 = h * f(x0 + h, y0 + k3);
y0 = y0 + (1/6) * (k1 + 2*k2 + 2*k3 + k4);
x0 = x0 + h;
end
fprintf('Solution at x = %f is y = %f\n', x0, y0);
Q28: Solve using ode45
f = @(x, y) x^2 + y^2;
[x, y] = ode45(f, [0, 1], 1);
plot(x, y);
xlabel('x');
ylabel('y');
title('Solution using ode45');
grid on;

Q29: Solve dy/dx = y/x, y(1) = 1 using ode45


f = @(x, y) y / x;
[x, y] = ode45(f, [1, 2], 1);
plot(x, y);
xlabel('x');
ylabel('y');
title('Solution using ode45');
grid on;

Q30: Solve dy/dx = (y-x)/(y+x), y(0) = 1 using ode45


f = @(x, y) (y - x) / (y + x);
[x, y] = ode45(f, [0, 2], 1);
plot(x, y);
xlabel('x');
ylabel('y');
title('Solution using ode45');
grid on;
%% Q31: Solve dy/dx = (y-x)/(y+x), y(0) = 1 using ode45
f = @(x, y) (y - x) / (y + x);
[x, y] = ode45(f, [0, 2], 1);
plot(x, y);
xlabel('x'); ylabel('y'); title('Solution using ode45'); grid on;

%% Matrix Operations
A = input('Enter first matrix: ');
B = input('Enter second matrix: ');

fprintf('Matrix Addition:\n');
disp(A + B);

fprintf('Matrix Subtraction:\n');
disp(A - B);

fprintf('Matrix Multiplication:\n');
disp(A * B);

fprintf('Matrix Inversion (if square and non-singular):\n');


if size(A,1) == size(A,2) && det(A) ~= 0
disp(inv(A));
else
disp('Matrix A is not invertible');
end
%% Fibonacci numbers up to first 10 terms
n = 10;
fib = zeros(1, n);
fib(1) = 0;
fib(2) = 1;
for i = 3:n
fib(i) = fib(i-1) + fib(i-2);
end
disp('First 10 Fibonacci numbers:');
disp(fib);

%% Q32: Convert degrees to radians


deg = input('Enter angle in degrees: ');
rad = deg2rad(deg);
fprintf('Angle in radians: %f\n', rad);

%% Q33: Plot x^3 - 3x + 2


x = linspace(-3, 3, 100);
y = x.^3 - 3*x + 2;
plot(x, y);
xlabel('x'); ylabel('y'); title('Graph of x^3 - 3x + 2'); grid on;

%% Q34: Solve x log(x) - 1.2 = 0 using Bisection Method


f = @(x) x * log(x) - 1.2;
a = 1; b = 2; tol = 1e-6;
while (b - a) / 2 > tol
c = (a + b) / 2;
if f(c) == 0
break;
elseif f(a) * f(c) < 0
b = c;
else
a = c;
end
end
fprintf('Root: %f\n', c);

%% Q35: Solve x sin(x) - 2 = 0


f = @(x) x * sin(x) - 2;
root = fzero(f, 1);
fprintf('Root: %f\n', root);

%% Q36: Solve x log(x) - 1.2 = 0 using Regula-Falsi Method


f = @(x) x * log(x) - 1.2;
a = 1; b = 2; tol = 1e-6;
while abs(f(b) - f(a)) > tol
c = (a * f(b) - b * f(a)) / (f(b) - f(a));
if f(c) == 0
break;
elseif f(a) * f(c) < 0
b = c;
else
a = c;
end
end
fprintf('Root: %f\n', c);

%% Q37: Solve system of linear equations using Gauss-Elimination


A = input('Enter coefficient matrix: ');
B = input('Enter constant matrix: ');
X = A \ B;
disp('Solution:'); disp(X);

%% Q38: Solve system using Gauss-Seidel Method


A = input('Enter coefficient matrix: ');
B = input('Enter constant matrix: ');
X = zeros(size(B));
tol = 1e-6;
maxIter = 100;
for k = 1:maxIter
X_old = X;
for i = 1:length(B)
X(i) = (B(i) - A(i, :) * X + A(i, i) * X(i)) / A(i, i);
end
if norm(X - X_old, inf) < tol
break;
end
end
disp('Solution:'); disp(X);

%% Q39: Solve system using Inverse Matrix Method


A = input('Enter coefficient matrix: ');
B = input('Enter constant matrix: ');
X = inv(A) * B;
disp('Solution:'); disp(X);

%% Q40: Find roots of a polynomial


coeffs = input('Enter polynomial coefficients: ');
roots_poly = roots(coeffs);
disp('Roots of polynomial:'); disp(roots_poly);

%% Q41: Approximate Pi using Series


n = 100000;
pi_approx = 4 * sum((-1).^(0:n) ./ (2 * (0:n) + 1));
fprintf('Approximated Pi: %.3f\n', pi_approx);

%% Q42: Solve system using inverse matrix (Duplicate of Q39)

%% Q43: Solve x log(x) - 1.2 = 0 using Newton-Raphson Method


f = @(x) x * log(x) - 1.2;
df = @(x) log(x) + 1;
x0 = 1.5;
while true
x1 = x0 - f(x0) / df(x0);
if abs(x1 - x0) < tol
break;
end
x0 = x1;
end
fprintf('Root: %f\n', x1);

%% Q44: Compute Correlation Coefficient


X = input('Enter X data: ');
Y = input('Enter Y data: ');
r = corrcoef(X, Y);
fprintf('Correlation Coefficient: %f\n', r(1, 2));

%% Q45: Compute Regression Line


X = input('Enter X data: ');
Y = input('Enter Y data: ');
p = polyfit(X, Y, 1);
fprintf('Regression Line: y = %f * x + %f\n', p(1), p(2));

%% Q46: Compute Best Fit Parabola y = a + bx + cx^2


p = polyfit(X, Y, 2);
fprintf('Best Fit Parabola: y = %f + %f*x + %f*x^2\n', p(3), p(2), p(1));

%% Q47: Compute Best Fit Exponential Curve y = a * exp(bx)


logY = log(Y);
p = polyfit(X, logY, 1);
fprintf('Best Fit Exponential Curve: y = %f * e^(%f * x)\n', exp(p(2)), p(1));

%% Q48: Compute Best Fit Line


disp('Same as Regression Line in Q45');

Common questions

Powered by AI

MATLAB uses iterative refinement in the Gauss-Seidel Method, updating each variable's value in-place during each iteration based on previous and current values. The process continues until the change between iterations is within a specified tolerance or a maximum number of iterations is reached. Compared to Gauss Elimination, Gauss-Seidel is better suited for sparse matrices and large systems, as it can require less memory and computation per iteration .

The correlation coefficient measures the strength and direction of a linear relationship between two variables. In MATLAB, it is computed using the corrcoef function, which returns a matrix where the off-diagonal element is the correlation coefficient between the data sets X and Y. This coefficient ranges from -1 to 1, where values close to 1 or -1 indicate strong relationships .

MATLAB uses the trapezoidal rule for numerical integration in this case. The function is defined as f(x) = exp(-x^2), and the integration is performed over the interval [0, 1]. The result of this integration using 101 points is approximately 0.747 .

The Newton-Raphson Method iteratively refines the estimate of the root using the formula x1 = x0 - f(x0)/f'(x0), applied to the equation f(x) = x * e^x - 2 with its derivative f'(x) = e^x * (x + 1). Starting from an initial approximation x0 = 0.5, the method converges rapidly if the initial guess is close enough to the actual root and the derivative does not become zero. The root is found to be approximately 0.8526 .

The Regula-Falsi Method, also known as the False Position Method, calculates the root by iteratively applying the formula c = (a * f(b) - b * f(a)) / (f(b) - f(a)), where f(x) = x - 2 * cos(x), starting with the interval [0, 1]. This method stops when the function value at c is near zero or when successive approximations are within a specified tolerance. It is efficient for functions with continuous derivatives and tends to converge faster than the Bisection Method due to its use of a linear interpolation approach. The root found is approximately 0.450 .

The ode45 function in MATLAB applies an adaptive step-size Runge-Kutta method to solve the differential equation dy/dx = y/x, starting from y(1) = 1. It automatically adjusts the step size to balance between accuracy and computation time, producing a solution over the specified range [1,2]. However, ode45 may struggle with stiff equations or problems where higher precision is necessary, possibly requiring a different solver or manual step-size adjustment .

MATLAB solves a system of linear equations using matrix inversion by expressing the solution as X = inv(A) * B, where A is the coefficient matrix and B is the constants matrix. While this method provides an exact solution for non-singular matrices, it can be computationally expensive and numerically unstable, especially for ill-conditioned matrices, due to roundoff errors and inversion operations .

Euler's Method approximates solutions to differential equations by iteratively stepping through the range [0, 1] with increments h = 0.1. For dy/dx = x^2 + y^2, starting from y(0) = 1, the next y value is obtained by computing y1 = y0 + h*f(x0, y0) at each step until reaching x = 1. The approximate solution thus obtained at x = 1 is around y = 3.04 .

Lagrange's Interpolation constructs a polynomial that passes through a given set of points by summing weighted terms. The method is theoretically sound and straightforward to implement for functions represented by discrete data points. However, its main drawbacks include inefficiency with large data sets due to the calculation of numerous terms and potential issues with polynomial oscillation (Runge's Phenomenon).

The Bisection Method iteratively narrows down the interval [1,2] by evaluating the midpoint and checking the product of function values at the endpoints to determine the subinterval that contains a root. This process continues until the interval is smaller than a certain tolerance level. The root calculated using this method is approximately 1.3247 .

You might also like