code:
clc
clear
% Define the time span
tspan = [0 10]; % Time span for the simulation (from 0 to 10 seconds)
v0 = 0;
% Solve the differential equation using ode45
[t, v] = ode45(@ode_function, tspan, v0);
% Plot the velocity as a function of time
plot(t, v)
xlabel('Time (s)');
ylabel('Velocity (m/s)');
title('Velocity vs. Time');
grid on;
function dvdt = ode_function(t, v)
% Define parameters
rho_B = 1000; % Density of the body (kg/m^3)
V_B = 0.01; % Volume of the body (m^3)
g = 9.81; % Gravitational acceleration (m/s^2)
rho_W = 1.225; % Density of the fluid (kg/m^3)
A_B = 0.1; % Cross-sectional area of the body (m^2)
m_B = rho_B * V_B; % Mass of the body (kg)
D_B = 0.2; % Diameter of the body (m)
visc_W = 1.789e-5; % Dynamic viscosity of the fluid (N*s/m^2)
% Calculate Reynolds number (Re)
Re = (rho_W * v * D_B) / visc_W;
% Calculate drag coefficient (C_D) using the given formula
C_D = (24/Re) + (2.6 * (Re/5) / (1 + (Re/5)^1.52)) + (0.41 * (Re/263000)^-7.94 / (1 + (Re/263000)^-8)) + (Re^0.8 / 461000);
% Calculate forces
F_B = rho_B * V_B * g;
F_D = (0.5 * rho_W * A_B * C_D) * v^2;
F_W = m_B * g;
% Calculate acceleration (dv/dt)
dvdt = (((F_B - F_D - F_W))/m_B);
end
This code is supposed to output a proper plot when used but instead all values for v
(except for the first one which is 0) are undefined/NaN. The problem is probably within the ode_function()
function but I'm not too experienced with ode45.
I tried editing how dvdt is defined and got proper results when changing it to a simpler equation such as 2t
but that's as far as I was able to get with a useful result.
By debugging with breakpoints (you should check out this yourself debugging in Matlab) i found out the following things:
You initiliaze v0=0
and use it in the ode_function as factor in Re = (rho_W * v * D_B) / visc_W
, hence Re=0
.
This leads to the formula C_D = (24/Re) + (2.6 * (Re/5) / (1 + (Re/5)^1.52)) + (0.41 * (Re/263000)^-7.94 / (1 + (Re/263000)^-8)) + (Re^0.8 / 461000)
where you divide by it (24/Re
-> Inf). Later in the formula you elevate Re ( one of the occasions is Re^0.8
-> Inf). This results in a Inf/Inf
-> NaN.
Due to this anything you do afternwards will just not produce any useful result, including the plot.
The simple solution is to not use 0 as input v0 and/or to validate (as <>0) it as the argument of the function