External Interfaces |
Calling MATLAB from a Fortran Application
This program, fengdemo.f
, illustrates how to call the engine functions from a stand-alone Fortran program.
C============================================================== = C fengdemo.f C C This program illustrates how to call the MATLAB C Engine functions from a Fortran program. C C Copyright (c) 1984-2000 by The MathWorks, Inc. C $Revision: 1.9 $ C============================================================== = program main integer engOpen, engClose, engEvalString integer engGetVariable, engPutVariable integer mxGetPr, mxCreateDoubleMatrix integer ep, T, D double precision time(10), dist(10) integer temp, status data time / 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0 / ep = engOpen('matlab ') if (ep .eq. 0) then write(6,*) 'Can''t start MATLAB engine' stop endif T = mxCreateDoubleMatrix(1, 10, 0) call mxCopyReal8ToPtr(time, mxGetPr(T), 10) C C Place the variable T into the MATLAB workspace. C status = engPutVariable(ep, 'T', T) if (status .ne. 0) then write(6,*) 'engPutVariable failed' stop endif C C Evaluate a function of time, distance = (1/2)g.*t.^2 C (g is the acceleration due to gravity). C if (engEvalString(ep, 'D = .5.*(-9.8).*T.^2;') .ne. 0) then write(6,*) 'engEvalString failed' stop endif C C Plot the result. C if (engEvalString(ep, 'plot(T,D);') .ne. 0) then write(6,*) 'engEvalString failed' stop endif if (engEvalString(ep, 'title(''Position vs. Time'')') .ne. 0) then write(6,*) 'engEvalString failed' stop endif if (engEvalString(ep, 'xlabel(''Time (seconds)'')') .ne. 0) then write(6,*) 'engEvalString failed' stop endif if (engEvalString(ep, 'ylabel(''Position (meters)'')') .ne. 0) then write(6,*) 'engEvalString failed' stop endif C C Read from console to make sure that we pause long enough to C be able to see the plot. C print *, 'Type 0 <return> to Exit' print *, 'Type 1 <return> to continue' read(*,*) temp if (temp.eq.0) then print *, 'EXIT!' stop end if if (engEvalString(ep, 'close;') .ne. 0) then write(6,*) 'engEvalString failed' stop endif D = engGetVariable(ep, 'D') call mxCopyPtrToReal8(mxGetPr(D), dist, 10) print *, 'MATLAB computed the following distances:' print *, ' time(s) distance(m)' do 10 i=1,10 print 20, time(i), dist(i) 20 format(' ', G10.3, G10.3) 10 continue call mxDestroyArray(T) call mxDestroyArray(D) status = engClose(ep) if (status .ne. 0) then write(6,*) 'engClose failed' stop endif stop end
Executing this program launches MATLAB, sends it data, and plots the results.
Entering 1
at the prompt continues the program execution.
1 MATLAB computed the following distances: time(s) distance(m) 1.00 -4.90 2.00 -19.6 3.00 -44.1 4.00 -78.4 5.00 -123. 6.00 -176. 7.00 -240. 8.00 -314. 9.00 -397. 10.0 -490.
Finally, the program frees memory, closes the MATLAB engine, and exits.
Examples of Calling Engine Functions | Attaching to an Existing MATLAB Session |
© 1994-2005 The MathWorks, Inc.