Converting Matlab Loops to Fortran

3 views (last 30 days)
Adam Harris
Adam Harris on 12 Sep 2021
Edited: Josh G. on 21 Sep 2021
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)
% 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
%% 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));
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!
Adam Harris
Adam Harris on 12 Sep 2021
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.

Sign in to comment.

Answers (1)

Josh G.
Josh G. on 21 Sep 2021
Edited: Josh G. on 21 Sep 2021
These will be straightforward do loops in Fortran:
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.





Community Treasure Hunt

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

Start Hunting!

Translated by