Converting Matlab Loops to Fortran

12 vues (au cours des 30 derniers jours)
Adam Harris
Adam Harris le 12 Sep 2021
Modifié(e) : Josh G. le 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)
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 commentaires
Image Analyst
Image Analyst le 12 Sep 2021
That's not a larger program -- it's tiny. I'd leave it in MATLAB.
Adam Harris
Adam Harris le 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.

Connectez-vous pour commenter.

Réponse acceptée

Josh G.
Josh G. le 21 Sep 2021
Modifié(e) : Josh G. le 21 Sep 2021
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.

Plus de réponses (0)

Catégories

En savoir plus sur Fortran with MATLAB dans Help Center et File Exchange

Tags

Produits


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by