MATLAB和前向欧拉方法

时间:2016-04-22 02:34:12

标签: arrays matlab

我正在编写一个使用前向欧拉方法来计算以下公式的代码:

dv(t)/ dt = g - (c_drag)(p_air / p_water)(3v(t)^ 2/4 * d)

我在下面的代码中概述了各种常量。

clear; 
clc; 
close all; 
% 1. Initialize
dt =  input('Enter the time step'); % choose delta t
t_start = 0; % starting time
t_end = 100;
g = 9.81;
y(1) = 0;
p_air = 1.2;
p_water = 1000;
c_drag = 0.517;
d = 0.002;
nstep = ( t_end - t_start ) / dt;% number of time steps
y = 1; % y(0) = 1, initial condition
all_t = ( 1 : nstep ) * dt; % all time points
all_FE_y = zeros( nstep , 1 ); % approximate solution - pre-allocation
all_exact_y = zeros( nstep , 1 ); % exact solution - pre-allocation
    % 2. Forward Euler time integration
    for n = 1 : nstep
      y(n+1) = y(n) + (dt * (g - (c_drag * (p_air / p_water) * ((3*(y(dt))^2)/ (4*d))))); % compute solution at time-step n+1
 all_FE_y (n) = y(n+1); % store solution
    end
    % 3. Compute the exact solution
    for n = 1 : nstep
     t = n * dt;
     all_exact_y (n) = exp(-t);
    end
    % 4. Write approximate solution on a file
    % 4.1. open file
    output_id = fopen('output_forward_Euler.txt', 'w');
    % 4.2. write a header
    fprintf(output_id, '%10s %10s %10s \r\n', 'Time', 'Approx', 'Exact' );
    % 4.3. write output
    fprintf(output_id, '%10.4f %10.6f %10.6f \r\n', [all_t; all_FE_y'; all_exact_y'] );
    % 4.4. close file
    fclose(output_id);
    % 5. Plot results
    % 5.1 plot settings
    set(0 ,'DefaultTextInterpreter' , 'latex' );
    set(0 ,'DefaultAxesUnits' , 'pixels');
    myFontSize = 14;
    myFontName = 'Helvetica' ;
    % The ScreenSize property value is a four-element vector: [left bottom width height]
    figure('Position', [100 100 500 500]);
    hold on
    % 5.2 plot exact and approximate solution
    plot(all_t,all_exact_y,'b', 'LineWidth',1)
    plot(all_t,all_FE_y, '--r','LineWidth',0.5)
    % 5.3 more plot settings
    set(gca,'Box' , 'on' ,...
     'Color' , 'white' ,...
     'LineWidth' , 0.5 ,...
     'TickDir' , 'in' ,...
     'XMinorTick' , 'on' , ...
     'YMinorTick' , 'on' , ...
     'XGrid' , 'on' , ...
     'YGrid' , 'on' , ...
     'XMinorGrid' , 'off' , ...
     'YMinorGrid' , 'off' , ...
     'XLim' , [ 0 4] , ...
     'YLim' , [ 0 1] , ...
     'XTick' ,linspace(0,4,5),...
     'YTick' ,linspace(0,1,6),...
     'TickLength' , [.02 .02] ,...
     'FontName' , myFontName ,...
     'FontSize' , myFontSize );
    % 5.4 background color
    set(gcf, 'color', 'white');
    % 5.5 labels
    xlabel('time (s)', 'FontName', myFontName, 'FontSize', myFontSize)
    ylabel('y (m)', 'FontName', myFontName, 'FontSize', myFontSize)
    % 5.6 legend
    hleg1 = legend('Exact','Approximation');
    set(hleg1,'Location','NorthEast')

我没有得到我期望的代码输出。它是否属于我的Euler方法或函数的其他部分?任何和所有的帮助将不胜感激!

0 个答案:

没有答案