MATLAB: Running, giving input and handling output of a FORTRAN program in MATLAB.

commandcommand linecommand promptexefortraninputMATLAB and Simulink Student Suiteoutputsystem

I want to compile my Fortran code so that I will be able to give inputs from MATLAB and use its output in MATLAB. The specifications of my Fortran code are
  1. It needs at least 4 inputs named a, b, c, d
  2. It should return at least 2 output complex matrices named Results and energy
I put read*, commands to give input in Fortran for all my required variables and used write(6,*) to display output matrices. Then I complied Fortran program into target.exe and run it in MATLAB by using
system('target.ex')
It asked me to give it inputs on Command Window and it showed output matrices. It worked. But I want to run this .exe in a loop for different values of inputs, how can I do that? Also, how can I store output matrices in MATLAB directly?
EDIT:
Taking output in form of write(6,*) is giving me very strange number, probably becuase output matrices are complex. Now, I am writing output in a file using write(22,*) <column1> <column2> command and it is storing output in file named fort.22. The fort.22 has values in the following form
1 (4.01868587018849865E-010,-7.09648826955835846E-010)
2 (4.01868587018849865E-010,-7.09648826955835846E-010)
and so on..
I want to take 1,2… as first column and values in the brackets as second column as my results. note: in (a,b) a is real part and b is imaginary part of the numerical value.
May be you know any other way to do the things that I am trying to do with write(22,*). I will be very thankful, If you share it with me.

Best Answer

On the fortran side, extract the real and complex portions and write them separately, like
write(22,*) column1, real(column2), aimag(column2)
With regards to getting input to fortran, then the method can depend upon which fortran compiler you are using. If you are using gfortran then you might need to set some environment variables; see https://www.mathworks.com/matlabcentral/answers/44388-or-system-or-unix-input-redirection#answer_56185
Typically you would do something like
tfile = tempname();
[fid, msg] = fopen(tfile, 'w');
if fid < 0
error('Failed opening temporary file "%s" because "%s"', tfile, msg)
end
fprintf(fid, '%g %g %g %g\n', a, b, c, d);
fclose(fid);
exe = 'target.exe';
cmd = sprintf('"%s" < "%s"', exe, tfile);
setenv(GFORTRAN_STDIN_UNIT, 5);
setenv(GFORTRAN_STDOUT_UNIT, 6);
[status, cmd_output] = system(cmd);
setenv(GFORTRAN_STDIN_UNIT, -1);
setenv(GFORTRAN_STDOUT_UNIT, -1);
results_back = cell2mat(textscan(cmd_output, '%f %f %f', 'CollectOutput', 1));
column_1 = results_back(:,1);
column_2 = complex(results_back(:,2), results_back(:,3));
Your Fortran code should read from unit 5 and write to unit 6.