Converting Matlab Loops to Fortran

조회 수: 12 (최근 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 CenterFile Exchange에서 Fortran with MATLAB에 대해 자세히 알아보기

태그

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by