Converting Matlab Loops to Fortran

17 ビュー (過去 30 日間)
Adam Harris
Adam Harris 2021 年 9 月 12 日
編集済み: Josh G. 2021 年 9 月 21 日
Hello! I'm just getting into Fortran coding and I'm trying to convert a Matlab program into Fortran. I understand that, more noticably for larger programs, Fortran compiles more quickly than Matlab. This will be useful for me in the future as I move into more elaborate problems. This program in Matlab solves and plots the 1D Heat equation using the Explicit Euler Method (Finite Difference). The Matlab code is as follows, excluding the plotting components:
%% Define Parameters
K = 5/33; % Thermal diffusivity
L = 2; % Length of 1D object
tf = 8; % Final time
% Set up spatial mesh
dx = 0.1; % Spatial step
Nx = L/dx % Number of intervals in space
% Set up temporal mesh based on desired stability
r = 0.5; % Desired stability ratio
dt = r*dx^2/(K*2) % Timestep found from desired stability ratio
Nt = round(tf/dt) % Number of intervals in time
%% Initial & Boundary Conditions
% Initial condition
for i = 1:Nx+1
x(i) = (i-1)*dx; % Define vector x
u(i,1) = 100*sin(pi*x(i)/2); % Define matrix u(x,t=0)=100sin(pi*x/2)
end
% Boundary conditions
for j = 1:Nt+1
u(1,j) = 0; % Left boundary condition u(x=0,t)=0
u(Nx+1,j) = 0; % Right boundary condition u(x=2,t)=0
t(j) = (j-1)*dt; % Define vector t
end
%% Explicit Euler's Method
for k = 1:Nt
for i = 2:Nx
u(i,k+1) = u(i,k) + 0.5*r*(u(i-1,k)+u(i+1,k)-2*u(i,k));
end
end
I've been able to define the parameters, timesteps, spatial steps, etc. I'm running into trouble converting these loops into Fortran. I'm using a GCC compiler with the "gfortran" command in the Terminal of my Mac, and my file types are .f95 . My only resources so far have been Google searches, so I'm hoping someone would be willing to walk me through the process of constructing these loops in Fortran.
Thank you so much!
  2 件のコメント
Image Analyst
Image Analyst 2021 年 9 月 12 日
That's not a larger program -- it's tiny. I'd leave it in MATLAB.
Adam Harris
Adam Harris 2021 年 9 月 12 日
That's not the point. I'm trying to learn Fortran and want to convert simple programs as practice. That way when I do have a larger program I have an idea of what to do.

サインインしてコメントする。

採用された回答

Josh G.
Josh G. 2021 年 9 月 21 日
編集済み: Josh G. 2021 年 9 月 21 日
These will be straightforward do loops in Fortran: https://www.tutorialspoint.com/fortran/fortran_do_loop.htm
Note that the loop index has to be an integer, but your length and dx variables are doubles. You have to ensure you convert to the right data type when defining the iterator limits.

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeFortran with MATLAB についてさらに検索

タグ

製品


リリース

R2020a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by