Project 1 - Data Handling and Interpolation
Project 1 :
% Prompt user for inputs (mass and spring constant)
prompt = {'Enter mass (m):', 'Enter spring constant (k):'};
dlgtitle = 'Input Parameters';
dims = [1 35];
definput = {'1', '1'}; % Default values
answer = inputdlg(prompt, dlgtitle, dims, definput);
% Convert inputs to numerical values
m = str2double(answer{1}); % Mass
k = str2double(answer{2}); % Spring constant
% Initial conditions
x0 = 1; % Initial displacement
v0 = 0; % Initial velocity
init_cond = [x0; v0];
% Time span for the simulation
tspan = [0, 10];
% Define the system of equations for the harmonic oscillator
sho_ode = @(t, x) [x(2); -(k/m)*x(1)]; % [dx/dt; d^2.x/dt^2]
%
% Solve using ode45
[t_45, x_45] = ode45(sho_ode, tspan, init_cond);
% Solve using ode23
[t_23, x_23] = ode23(sho_ode, tspan, init_cond);
% Compute acceleration (xdotdot = -(k/m) * x)
acc_45 = -(k/m) * x_45(:, 1);
acc_23 = -(k/m) * x_23(:, 1);
% Plot results
figure; % By putting figure command everytime code is run with
% different m & k it will produce each time on different page
% Plot displacement
subplot(321);
plot(t_45, x_45(:, 1), 'b'); % x_45 column 1 consists of displacement (x)
title('x(ode45)');
xlabel('Time (t)');
ylabel('x(t)');
grid on;
subplot(322);
plot(t_23, x_23(:, 1), 'r'); % x_23 column 1 consists of displacement (x)
title('x(ode23)');
xlabel('Time(t)');
ylabel('x(t)');
grid on;
% Plot velocity
subplot(323);
plot(t_45, x_45(:, 2), 'b'); % x_45 column 2 consists of velocity (xdot)
title('xdot(ode45)');
xlabel('Time(t)');
ylabel('xdot(t)');
grid on;
subplot(324);
plot(t_23, x_23(:, 2), 'r'); % x_23 column 2 consists of velocity (xdot)
title('xdot(ode23)');
xlabel('Time(t)');
ylabel('xdot(t)');
grid on;
% Plot acceleration
subplot(325);
plot(t_45, acc_45, 'b');
title('xdotdot(ode45)');
xlabel('Time(t)');
ylabel('xdotdot(t)');
grid on;
subplot(326);
plot(t_23, acc_23, 'r');
title('xdotdot(ode23)');
xlabel('Time(t)');
ylabel('xdotdot(t)');
grid on;
% Comparison Explanation
disp('Comparison between ode45 and ode23:');
disp('1. ode45 is generally more accurate than ode23 because it uses a higher-order Runge-Kutta method.');
disp('2. ode23 is faster but may lose accuracy for stiff or highly oscillatory problems.');
disp('3. In this example, both solvers provide nearly identical results because the SHO equation is smooth and not stiff.');
Project 2 :
function R_squared = goodnessOfFit(actual, predicted)
% goodnessOfFit - Calculates the coefficient of determination (R²).
%
% Syntax: R_squared = goodnessOfFit(actual, predicted)
%
% Inputs:
% actual - Vector of actual data points.
% predicted - Vector of predicted data points from the model.
%
% Output:
% R_squared - Coefficient of determination (R²).
% Check that the inputs are vectors of the same size
if length(actual) ~= length(predicted)
error('Input vectors must be of the same length.');
end
% Calculate total sum of squares (SST) and residual sum of squares (SSR)
SST = sum((actual - mean(actual)).^2); % Total sum of squares
SSR = sum((actual - predicted).^2); % Residual sum of squares
% Compute R²
R_squared = 1 - (SSR / SST);
end
% Altitude vs Temperature Analysis with Regression and Plotting
% Step 1: Load altitude vs temperature data (sample data used here as hyperlink in challenge is not working)
% Replace this section with actual ISA table data.
data = readtable('AltitudevsTemperature.xlsx'); %readtable() function used map voltage & current directly to V & I.
altitude = data.Altitude; % Directly taken data of Altitude from 'data' variable
temperature = data.Temperature; % Directly taken data of Temperature from 'data' variable
% Step 2: Use polyfit to determine a regression model: T = f(h)
degree = 1; % Linear fit (can be adjusted for higher-degree fits if needed)
coefficients = polyfit(altitude, temperature, degree); % Determine regression model
% Step 3: Evaluate the model using polyval
evaluated_temp = polyval(coefficients, altitude);
% Step 4: Determine the goodness of fit using the custom function
R_squared = goodnessOfFit(temperature, evaluated_temp);
% Display goodness of fit
fprintf('Goodness of fit (R-squared): %.4f\n', R_squared);
% Step 5: Generate comparative plot
figure;
plot(altitude, temperature, 'bo-'); hold on;
plot(altitude, evaluated_temp, 'r--');
title('Altitude vs Temperature');
xlabel('Altitude (m)');
ylabel('Temperature (°C)');
legend('show');
grid on;
% Step 6: Store evaluated data into a text file
output_filename = 'evaluated_data.txt';
fid = fopen(output_filename, 'w'); % Open file for writing
if fid == -1
error('Could not open file for writing.');
end
% Write header (optional)
fprintf(fid, 'Altitude (m)\tEvaluated Temperature (°C)\n');
% Write data to file
len = length(evaluated_temp);
for i = 1:len
fprintf(fid, '%.2f \t%.4f\n', altitude(i), evaluated_temp(i)); % Save data with 4 decimal precision
end
% Close file
fclose(fid);
fprintf('Evaluated data saved to file: %s\n', output_filename);
Project 3 :
% Main script to evaluate, plot, and find extrema of the function
clc;
clear;
close all;
% Define the function as a handle
f = @(x) sin(x.^2) + cos(x) - 2*sin(x).*cos(x);
% Define the range for evaluation and plotting
x = linspace(-5, 5, 1000); % Range for x
y = f(x); % Evaluate the function
% Plot the function
figure;
plot(x, y, 'b-', 'LineWidth', 1.5);
hold on;
grid on;
xlabel('x');
ylabel('y');
title('y = sin(x^2) + cos(x) - 2sin(x)cos(x)');
legend('y(x)');
% Find the global maxima
[max_y, max_idx] = max(y);
x_max = x(max_idx);
plot(x_max, max_y, 'ro', 'MarkerSize', 8, 'DisplayName', 'Global Maxima');
gtext(sprintf('Global Maxima: (%.2f, %.2f)', x_max, max_y));
% Find local minima using fminsearch
local_minima_x = []; % To store local minima x-coordinates
local_minima_y = []; % To store local minima y-values
% Initial guesses for local minima
initial_guesses = -4.5:1:4.5; % Sample points in the range
for i = 1:length(initial_guesses)
% Find minima using fminsearch
x_min = fminsearch(f, initial_guesses(i));
y_min = f(x_min);
% Avoid duplicate minima and check if it's within range
if all(abs(local_minima_x - x_min) > 1e-2) && x_min >= -5 && x_min <= 5
local_minima_x = [local_minima_x, x_min];
local_minima_y = [local_minima_y, y_min];
end
end
% Plot and annotate local minima
for i = 1:length(local_minima_x)
plot(local_minima_x(i), local_minima_y(i), 'go', 'MarkerSize', 8, 'DisplayName', 'Local Minima');
gtext(sprintf('Local Minima: (%.2f, %.2f)', local_minima_x(i), local_minima_y(i)));
end
% Finalize plot
legend('show');
hold off;
% Display results
fprintf('Global Maxima: x = %.4f, y = %.4f\n', x_max, max_y);
fprintf('Local Minima:\n');
for i = 1:length(local_minima_x)
fprintf('x = %.4f, y = %.4f\n', local_minima_x(i), local_minima_y(i));
end
Project 4 :
% The contour command in MATLAB is used to create contour plots, which are 2D representations of 3D surface data.
% Contour plots display level curves where a function f(x,y) maintains a constant value. These plots are
% particularly useful for visualizing scalar fields, such as temperature distributions or potential fields.
% Basic Syntax:
% 1. contour(X, Y, Z): Plots contour lines for the function Z=f(X,Y), where X and Y are grid matrices.
% 2. contour(Z): Uses a default grid for X and Y.
% Customization:
% The number of contour levels can be controlled with an additional argument: contour(X, Y, Z, n), where n specifies the number of levels.
% Contours can be labeled with the clabel function.
% Filled Contours:
% The contourf command creates filled contour plots, which provide a visually rich representation.
% Applications:
% Visualizing mathematical functions.
% Analyzing terrain elevation maps.
% Plotting solutions to partial differential equations.
% Example of Contour Plot
clc;
clear;
close all;
% Define the grid
x = linspace(-5, 5, 100); % Range for x
y = linspace(-5, 5, 100); % Range for y
[X, Y] = meshgrid(x, y); % Create grid matrices
% Define a 3D surface function
Z = sin(sqrt(X.^2 + Y.^2)) ./ sqrt(X.^2 + Y.^2);
% Create a basic contour plot
figure;
contour(X, Y, Z, 20, 'LineWidth', 1.5); % 20 contour levels
colorbar; % Add a colorbar for reference
title('Contour Plot of Z = sin(sqrt(X^2 + Y^2)) / sqrt(X^2 + Y^2)');
xlabel('X-axis');
ylabel('Y-axis');
grid on;
% Add labels to the contours
clabel(contour(X, Y, Z, 10), 'FontSize', 8); % Add labels to 10 levels