MATLAB Exercise
Solution
1. Problem 1
% Compute A
A = (3*sqrt(3)/4) + 24 * ( (1/12) - (1/(5*2^5)) - (1/(28*2^7)) - (1/(72*2^9)) );
% Compute B
B = 3 + (1/60) * ( 8 + (2*3)/(7*8*3) * (13 + (3*5)/(10*11*3) * (18 + (4*7)/(13*14*3)))
);
% Display results
fprintf('A = %.6f\n', A);
fprintf('B = %.6f\n', B);
2. Problem 2
WITH NO INPUT
% MATLAB script to compute x, y, and z
% Compute x
x = (2*sqrt(3))/5;
% Compute y
y = (2*pi)/exp(-x^3 / 3);
% Compute z
z = 4*x + log10(2*y);
% Display results
fprintf('x = %.6f\n', x);
fprintf('y = %.6f\n', y);
fprintf('z = %.6f\n', z);
CUSTOM INPUT
% MATLAB script to compute x, y, and z with user input
% User input for x, y, and z
x = input('Enter x: ');
y = input('Enter y: ');
z = input('Enter z: ');
% Display results
fprintf('Computed values:\n');
fprintf('x = %.6f\n', x);
fprintf('y = %.6f\n', y);
fprintf('z = %.6f\n', z);
“%” indicates that a format specifier is being used, ”.6” means that 6 digits after the decimal
point will be shown. “f” stands for floating-point numbers, meaning the numbers will be
displayed in a decimal format.
3. Problem 3
%No input
A = [4, -6, 5; -6, 15, -3; 2, -7, 13];
B = [1, 4, -5; 2, 23, 7; -5, 9, 19];
% Part (a): Input Matrices A and B
rowsA = input('Enter the number of rows for matrix A: ');
colsA = input('Enter the number of columns for matrix A: ');
A = zeros(rowsA, colsA);
disp('Enter elements for matrix A:');
for i = 1:rowsA
for j = 1:colsA
A(i, j) = input(sprintf('A(%d,%d): ', i, j));
end
end
rowsB = input('Enter the number of rows for matrix B: ');
colsB = input('Enter the number of columns for matrix B: ');
B = zeros(rowsB, colsB);
disp('Enter elements for matrix B:');
for i = 1:rowsB
for j = 1:colsB
B(i, j) = input(sprintf('B(%d,%d): ', i, j));
end
end
% Display matrices
disp('Matrix A:');
disp(A);
disp('Matrix B:');
disp(B);
% Part (b): Determine the inverse of A and B if possible
if rowsA == colsA && det(A) ~= 0
A_inv = inv(A);
disp('Inverse of A:');
disp(A_inv);
else
disp('Matrix A is not invertible.');
end
if rowsB == colsB && det(B) ~= 0
B_inv = inv(B);
disp('Inverse of B:');
disp(B_inv);
else
disp('Matrix B is not invertible.');
end
% Part (c): Compute the sum of A and B (only if same dimensions)
if rowsA == rowsB && colsA == colsB
sumAB = A + B;
disp('Sum of A and B:');
disp(sumAB);
else
disp('Cannot add A and B: Dimensions do not match.');
end
% Part (d): Compute the product of A and B (if dimensions are compatible)
if colsA == rowsB
prodAB = A * B;
disp('Product of A and B:');
disp(prodAB);
else
disp('Cannot multiply A and B: Incompatible dimensions.');
end
4. Problem 4
NO INPUT
y = 2*x^6 - 3*x^4 + 4*x^2 - 1988
solve(y == 0)
double(ans)
% Display results
fprintf('x = %.6f\n', ans);
CUSTOM INPUT
% User input y
y = input('Enter y = ');
solve(y == 0)
double(ans)
% Display results
fprintf('x = %.6f\n', ans);
5. Problem 5
NO INPUT
% Define the coefficient matrix A
A = [2 1 1;
-1 1 -1;
1 2 3];
% Define the constant vector b
B = [2; 3; -10];
% Solve the system of equations using the backslash operator
solution = A \ B;
% Extract the values of x, y, z
x = solution(1);
y = solution(2);
z = solution(3);
% Display the results
fprintf('The solution to the system of equations is:\n');
fprintf('x = %.0f\n', x);
fprintf('y = %.0f\n', y);
fprintf('z = %.0f\n', z);
CUSTOM INPUT
% Part (a): Input Matrices A and B
rowsA = input('Enter the number of rows for matrix A: ');
colsA = input('Enter the number of columns for matrix A: ');
A = zeros(rowsA, colsA);
disp('Enter elements for matrix A:');
for i = 1:rowsA
for j = 1:colsA
A(i, j) = input(sprintf('A(%d,%d): ', i, j));
end
end
rowsB = input('Enter the number of rows for matrix B: ');
colsB = input('Enter the number of columns for matrix B: ');
B = zeros(rowsB, colsB);
disp('Enter elements for matrix B:');
for i = 1:rowsB
for j = 1:colsB
B(i, j) = input(sprintf('B(%d,%d): ', i, j));
end
end
% Display matrices
disp('Matrix A:');
disp(A);
disp('Matrix B:');
disp(B);
% Solve the system of equations using the backslash operator
solution = A \ B;
% Extract the values of x, y, z
x = solution(1);
y = solution(2);
z = solution(3);
% Display the results
fprintf('The solution to the system of equations is:\n');
fprintf('x = %.0f\n', x);
fprintf('y = %.0f\n', y);
fprintf('z = %.0f\n', z);
6. Problem 6
% Define the system of equations
f1 = @(y) asin(1.2 - cos(y));
f2 = @(x) (4 - 2*x) / 3;
% Initial guess
x0 = 0;
y0 = 0;
% Tolerance for convergence
tolerance = 1e-6;
% Maximum number of iterations
max_iterations = 100;
% Initialize variables
x_old = x0;
y_old = y0;
iteration = 0;
disp('Iteration | x | y |');
disp('-----------------------------------------');
while iteration < max_iterations
% Jacobi iteration
x_new = f1(y_old);
y_new = f2(x_old);
fprintf('%9d | %11.7f | %11.7f |\n', iteration, x_old, y_old);
% Check for convergence
if abs(x_new - x_old) < tolerance && abs(y_new - y_old) < tolerance
break;
end
% Update values for the next iteration
x_old = x_new;
y_old = y_new;
iteration = iteration + 1;
end
fprintf('\nSolution found after %d iterations:\n', iteration);
fprintf('x = %f\n', x_new);
fprintf('y = %f\n', y_new);
% Check the solution
eq1_check = sin(x_new) + cos(y_new);
eq2_check = 2*x_new + 3*y_new;
fprintf('\nChecking the solution:\n');
fprintf('sin(x) + cos(y) = %f (should be 1.2)\n', eq1_check);
fprintf('2x + 3y = %f (should be 4)\n', eq2_check);
7. Problem 7
% MATLAB program to determine student's grade based on score
clear; % Clear workspace
clc; % Clear command window
% Prompt user to input the score
score = input('Enter the student''s score (0-100): ');
% Check if the score is within valid range (0 to 100)
if score < 0 || score > 100
fprintf('Error: Score must be between 0 and 100.\n');
else
% Determine the grade based on the score
if score >= 95
grade = 'A';
elseif score >= 80 && score < 95
grade = 'B';
elseif score >= 60 && score < 80
grade = 'C';
else
grade = 'D';
end
% Display the result
fprintf('The student''s grade is: %s\n', grade);
end
8. Problem 8
% MATLAB program to compute, display, and plot the finite Fourier series
% y(x) = sum_{n=1}^{1000} sin(nx)/n over the interval x = (0, 8pi)
% Step 1: Define the interval and number of points
x = linspace(0, 8*pi, 1000); % Creates 1000 points from 0 to 8pi
y = zeros(size(x)); % Initialize y(x) array with zeros
% Step 2: Compute the Fourier series sum
for n = 1:1000
y = y + sin(n*x)/n; % Add each term sin(nx)/n to the sum
end
% Step 3: Display the sum at specific x-values (e.g., at x = pi, 2pi, ..., 8pi)
x_points = pi:pi:8*pi; % Points to evaluate: pi, 2pi, ..., 8pi
fprintf('Values of the Fourier series sum y(x) = sum_{n=1}^{1000} sin(nx)/n:\n');
fprintf('-------------------------------------------------\n');
fprintf('x\t\t\ty(x)\n');
fprintf('-------------------------------------------------\n');
for i = 1:length(x_points)
% Find the index of the closest x-value in the array to x_points(i)
[~, idx] = min(abs(x - x_points(i)));
fprintf('%.4f\t\t%.4f\n', x_points(i), y(idx));
end
fprintf('-------------------------------------------------\n');
% Step 4: Plot the result
figure;
plot(x, y, 'b-', 'LineWidth', 2); % Plot y(x) in blue with a thick line
grid on;
xlabel('x');
ylabel('y(x)');
title('Finite Fourier Series: y(x) = \Sigma_{n=1}^{1000} sin(nx)/n');
xlim([0, 8*pi]); % Set x-axis limits to the interval (0, 8pi)
9. Problem 9
n = 0;
sum_divided_by_3 = 0;
while (sum_divided_by_3 < 1000)
n = n + 1;
sum_of_cubes = sum(n.^3); % Calculate the sum of cubes from 1 to n
sum_divided_by_3 = sum_of_cubes / 3;
end
% The loop continues one step after the sum exceeds or equals 1000,
% so the maximum value of n is the previous value.
max_n = n - 1;
fprintf('The maximum value of n is: %d\n', max_n);
10. Problem 10
% Define the range of x values
x = linspace(-10, 10, 100); % Create 100 evenly spaced points between -10 and 10
% Calculate the corresponding y values
y = 2 * exp(-0.2 * x) + x.^2;
% Plot the 2D graph
plot(x, y);
% Add labels for the axes
xlabel('x');
ylabel('y');
% Add a title to the plot
title('Plot of y = 2e^{-0.2x} + x^2');
% Optional: Add a grid for better readability
grid on;