LFortran: Translating Fortran to MATLAB?

If I remember correctly, LFortran will support generating Python from Fortran, which is fantastic.

Would the LFortran team consider other languages, e.g., MATLAB?

Modern Fortran is super similar to MATLAB, much more than Python. Below is an example. If translation to Python is possible, then doing the same for MATLAB should be imaginable.

Thanks.

function solve(A, b) result(x)  ! A naive Fortran solver for upper-triangle linear systems
implicit none
real, intent(in) :: A(:, :), b(:)
real :: x(size(A, 2))
integer :: i, n

n = size(x) 

x(n) = b(n) / A(n, n);
do i = n-1, 1, -1
    x(i) = (b(i) - dot_product(A(i, i + 1:n), x(i + 1:n))) / A(i, i)
end do

end function solve
function x = solve(A, b)   ! A naive MATLAB solver for upper-triangle linear systems

x = NaN(size(A, 2), 1);

n = length(x) ;

x(n) = b(n) / A(n, n);
for i = n-1 : -1 : 1
    x(i) = (b(i) - A(i, i + 1:n)'*x(i + 1:n)) / A(i, i);
end 
2 Likes

Speculation: Ben Barrow might be interested because of his semiautomatic Fortran to Matlab translator f2matlab he introduces with

f2matlab is the only semiautomatic fortran to Matlab translator in the world. It is usually sufficient for the conversion of small programs when followed by manual cleanup, debugging, and validation.

According to project counter on MathWorks, the current version is 4.1.0.1 (5 Mar 2021) with a total of 23.2k downloads over all versions released.

Sure, I am aware of f2matlab, but I believe that LFortran can do much better.

Yes, we can do that. Just write an ASR->Matlab backend, similar to the existing ASR->Julia backend. Regarding maintenance, for now it would be the best if this is handled in a separate project and you simply update the backend from time to time to work with a given LFortran version.

2 Likes

Thank you @certik for your response. That sounds great!

It would be great if someone is interested in initiating such a project. I am afraid that I do not know low-level stuff like AST. It would substantially increase the impact of LFortran. MATLAB is (still) extremely popular in education, research, scientific computing, industry, and engineering.

2 Likes

Just implement a file like this one: lfortran/asr_to_julia.cpp at 01b73167d83002c7851b511ceaa54104870bc5d4 · lfortran/lfortran · GitHub, but instead of Julia code, generate Matlab code, as a string. That’s the easiest. You can do it on a branch, even submit a PR. I just don’t want to merge and maintain such backends right now, until LFortran can compile all Fortran codes, as every backend increases maintenance and I don’t want to spread too thin. But if you either maintain it on a branch, or we’ll restructure things so that you depend on LFortran as a dependency and maintain it in a separate project, then there is no maintenance overhead on our end and we should do it!

1 Like