In: Computer Science
Write a MATLAB script file to numerically solve any first order initial value problem using Rulers method. Once code is working use it to solve the mixing tank problem below. Use a step size of 1 minute, and simulate the solution until the tank contains no more salt. Plot both the Euler approximation and the exact solution on the same set of axes.
A tank contains 100 gallons of fresh water. At t=0 minutes, a solution containing 1 lb/gal of brine is pumped into the tank at a rate of 1 gal/min. while the mixture is pumped out at a rate of 2 gal/min. Model the corresponding initial value problem, and then determine the amount of salt in the tank as a function of time until the tank is empty.
Let y be the concentration of salt. Hence the rate at which the concentration varies can be expressed as
with
Hence the ODE can be written as
Solve for y
Apply initial conditions y(0) = 0
at t =100 y will be zero
Matlab code
f = @(y,t) 1-2*y/(100-t); % The rhs function
h = 1; % step size
t = 0:h:100; % the t vector [0,100] with an increment h= 1
y(1) = 0; % initial condition
for k =2:length(t)% loop for computing y
y(k) = y(k-1)+h*f(y(k-1),t(k-1)); % computing
the solution at each step
end
plot(t,y);% plotting y vs t with h =1
hold on; % adding two graphs in a same plot
y = (100-t)-((100-t).^2)./100; % Exact solution
plot(t,y);% plotting exact solution
xlabel('t');% labeling x axis
ylabel('y');% labeling y label
legend('Euler','Exact');% adding legend to the plot
Output