Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
4 views8 pages

Matlab

The document contains MATLAB code for two numerical methods: the Gauss-Seidel method for solving a system of equations and the Newton-Raphson method for solving a vertical settlement problem. Each method includes initialization, iteration loops, convergence checks, and plotting of results. The code outputs the final solutions and generates convergence plots for both methods.

Uploaded by

Aarthi B
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)
4 views8 pages

Matlab

The document contains MATLAB code for two numerical methods: the Gauss-Seidel method for solving a system of equations and the Newton-Raphson method for solving a vertical settlement problem. Each method includes initialization, iteration loops, convergence checks, and plotting of results. The code outputs the final solutions and generates convergence plots for both methods.

Uploaded by

Aarthi B
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
You are on page 1/ 8

Code:

% MATLAB code for generating a convergence plot of Gauss-Seidel method

% Define the coefficients and constants for the system of equations


% 1. 15x + 3y - 2z = 210
% 2. -4x + 12y + z = 120
% 3. x - y + 10z = 90

% Rearranged equations for Gauss-Seidel:


% x = (210 - 3y + 2z) / 15
% y = (120 + 4x - z) / 12
% z = (90 - x + y) / 10

% Initial guesses
x = 0;
y = 0;
z = 0;

% Store values for plotting


x_values = x;
y_values = y;
z_values = z;

% Parameters for convergence


tolerance = 1e-6; % Desired accuracy (6 decimal places)
max_iterations = 100; % Maximum number of iterations

fprintf('Iteration | x | y | z \n');
fprintf('----------------------------------------------------------------\n');
fprintf('%6d | %13.6f | %13.6f | %13.6f \n', 0, x, y, z);

% Gauss-Seidel Iteration Loop


for iter = 1:max_iterations
x_old = x;
y_old = y;
z_old = z;

% Update x using current y and z


x = (210 - 3*y_old + 2*z_old) / 15;

% Update y using current x (the newly calculated x) and current z


y = (120 + 4*x - z_old) / 12;

% Update z using current x (the newly calculated x) and current y (the newly calculated y)
z = (90 - x + y) / 10;

% Append current values for plotting


x_values = [x_values; x];
y_values = [y_values; y];
z_values = [z_values; z];

fprintf('%6d | %13.6f | %13.6f | %13.6f \n', iter, x, y, z);

% Check for convergence


if abs(x - x_old) < tolerance && ...
abs(y - y_old) < tolerance && ...
abs(z - z_old) < tolerance
fprintf('\nConvergence achieved after %d iterations.\n', iter);
break;
end
end
if iter == max_iterations
fprintf('\nMaximum number of iterations reached. Solution may not have converged to the
desired tolerance.\n');
end

fprintf('\nFinal Solution (accurate to 6 decimal places):\n');


fprintf('x = %.6f L/s\n', x);
fprintf('y = %.6f L/s\n', y);
fprintf('z = %.6f L/s\n', z);

% --- Create the convergence plot ---


figure; % Create a new figure window
plot(0:length(x_values)-1, x_values, '-o', 'MarkerSize', 4, 'DisplayName', 'x');
hold on; % Keep the current plot and add new plots
plot(0:length(y_values)-1, y_values, '-s', 'MarkerSize', 4, 'DisplayName', 'y');
plot(0:length(z_values)-1, z_values, '-^', 'MarkerSize', 4, 'DisplayName', 'z');
hold off; % Release the hold on the plot

xlabel('Iteration');
ylabel('Value');
title('Convergence Plot of Gauss-Seidel Method');
legend('Location', 'best'); % Display legend
grid on; % Add a grid to the plot

% Optional: Save the plot to a file


% saveas(gcf, 'gauss_seidel_convergence_plot_matlab.png');
% fprintf('Convergence plot saved as gauss_seidel_convergence_plot_matlab.png\n');
Output:

Convergence Plot:
Code:

% MATLAB code for solving the vertical settlement problem using Newton-Raphson method
% This version avoids scientific notation ('e') for f(s_n) and f'(s_n)
% and removes the Error column from the table output.
% Convergence is still to 6 decimal places.

% --- 1. Define the function f(s) and its derivative df(s) ---
% Constants given in the problem
k = 100;
P = 1500;

% Anonymous function for f(s)


f = @(s) k * s.^3 - P * s + 5;

% Anonymous function for the derivative f'(s)


df = @(s) 3 * k * s.^2 - P;

% --- 2. Initialize Parameters ---


s = 1.0; % Initial guess s_0
tolerance = 1e-6; % Desired accuracy (6 decimal places)
max_iterations = 100; % Maximum number of iterations

% Store 's' values for convergence plot


s_history = s;

% --- 3. Newton-Raphson Iteration Loop ---


% Updated header: Removed 'Error' column
fprintf('%-10s | %-25s | %-25s | %-25s\n', 'Iteration', 's_n', 'f(s_n)', 'f''(s_n)');
fprintf('%s\n', repmat('-', 95, 1)); % Separator line, adjusted length

for i = 0:max_iterations-1
f_s = f(s);
df_s = df(s);

% Check for derivative being too close to zero


if abs(df_s) < 1e-15 % Using a small threshold to avoid division by zero
warning('Derivative is too close to zero. Newton-Raphson method may fail or converge
slowly.');
break;
end

s_new = s - f_s / df_s;


error = abs(s_new - s); % Calculate error internally, but not print

% Updated print line: Removed 'error' value, changed 'e' to 'f' for f(s_n) and f'(s_n)
% Use enough decimal places for f and df to show precision without 'e'
fprintf('%-10d | %-25.15f | %-25.10f | %-25.10f\n', i, s, f_s, df_s);

% Store for plotting


s_history = [s_history; s_new]; %#ok<AGROW>

% Check for convergence based on the requested tolerance (6 decimal places)


if error < tolerance
fprintf('\nConvergence achieved.\n');
s = s_new; % Update to the converged value
break;
end

s = s_new; % Update s for the next iteration


end
if i == max_iterations - 1 && error >= tolerance
fprintf('\nMaximum iterations reached without achieving desired tolerance.\n');
end

% Final result formatted to 6 decimal places


fprintf('\nFinal calculated settlement (s): %.6f cm\n', s);
fprintf('Number of iterations: %d\n', i + 1);

% --- 4. Generate Convergence Plot ---


figure; % Create a new figure window
plot(0:length(s_history)-1, s_history, '-o', 'MarkerSize', 5, 'LineWidth', 1.5, 'Color', [0
0.4470 0.7410]);
hold on; % Keep the current plot for adding more elements

% Plot the final converged value as a horizontal line for reference


plot(xlim, [s s], '--r', 'LineWidth', 1, 'DisplayName', sprintf('Converged Value (%.6f)',
s)); % Display to 6 decimal places

xlabel('Iteration Number');
ylabel('Settlement s (cm)');
title(sprintf('Newton-Raphson Method Convergence (Tolerance: %.0e)', tolerance));
grid on;
legend('s_n', 'Converged Value', 'Location', 'best');
set(gca, 'FontSize', 12); % Adjust font size for readability
Output:

Convergence Plot:
23CE33C- STATISTICS AND NUMERICAL METHODS
CO-4 MATLAB ASSIGNMENT

BY
AARTHI.B
24103001
SECOND YEAR CIVIL

You might also like