MATLAB Api Guide
MATLAB Api Guide
MATLAB Api Guide
Visualization
Programming
Application Program I nterface Guide
Version 5
How to Contact The MathWorks:
508-647-7000 Phone
508-647-7001 Fax
The MathWorks, I nc. Mai l
24 Pri me Park Way
Nati ck, MA 01760-1500
http://www.mathworks.com Web
ftp.mathworks.com Anonymous FTP server
comp.soft-sys.matlab Newsgroup
support@mathworks.com Techni cal support
suggest@mathworks.com Product enhancement suggesti ons
bugs@mathworks.com Bug reports
doc@mathworks.com Documentati on error reports
subscribe@mathworks.com Subscri bi ng user regi strati on
service@mathworks.com Order status, l i cense renewal s, passcodes
info@mathworks.com Sal es, pri ci ng, and general i nformati on
Application ProgramI nterfaceGuide
COPYRI GHT 1984 - 1998 by The MathWor ks, I nc.
The softwar e descr i bed i n thi s document i s fur ni shed under a l i cense agreement. The software may be used
or copi ed onl y under the terms of the l i cense agr eement. No par t of thi s manual may be photocopi ed or r epr o-
duced i n any form wi thout pr i or wr i tten consent from The MathWor ks, I nc.
U.S. GOVERNMENT: I f Li censee i s acqui r i ng the Progr ams on behal f of any uni t or agency of the U.S.
Gover nment, the fol l owi ng shal l appl y: (a) For uni ts of the Depar tment of Defense: the Gover nment shal l
have onl y the ri ghts speci fi ed i n the l i cense under whi ch the commerci al computer softwar e or commer ci al
softwar e documentati on was obtai ned, as set for th i n subpar agr aph (a) of the Ri ghts i n Commer ci al
Computer Softwar e or Commer ci al Softwar e Documentati on Cl ause at DFARS 227.7202-3, ther efor e the
ri ghts set for th her ei n shal l appl y; and (b) For any other uni t or agency: NOTI CE: Notwi thstandi ng any
other l ease or l i cense agr eement that may per tai n to, or accompany the del i ver y of, the computer software
and accompanyi ng documentati on, the ri ghts of the Gover nment regar di ng i ts use, r epr oducti on, and di scl o-
sure are as set for th i n Cl ause 52.227-19 (c)(2) of the FAR.
MATLAB, Si mul i nk, Statefl ow, Handl e Gr aphi cs, and Real -Ti me Workshop ar e r egi stered trademar ks, and
Tar get Language Compi l er i s a trademar k of The MathWor ks, I nc.
Other pr oduct or br and names are tr ademar ks or r egi stered tr ademar ks of thei r respecti ve hol der s.
Pri nti ng Hi story: December 1996 Fi r st pr i nti ng
Jul y 1997 Revi sed for 5.1 (onl i ne onl y)
Januar y 1998 Second pri nti ng Revi sed for MATLAB 5.2
October 1998 Thi rd pri nti ng Revi sed for MATLAB 5.3 (Rel ease 11)
i
Contents
1
IntroducingtheMATLAB API
Introduction to MATLAB API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2
MEX-Fi l es . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2
MAT-Fi l e Appl i cati ons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2
Engi ne Appl i cati ons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-3
MATLAB Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-4
The MATLAB Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-4
Data Storage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-4
Data Types i n MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-5
Compl ex Doubl e-Preci si on Matri ces . . . . . . . . . . . . . . . . . . . 1-5
Numeri c Matri ces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-5
MATLAB Stri ngs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-5
Sparse Matri ces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-5
Cel l Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-6
Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-6
Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-6
Mul ti di mensi onal Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-6
Logi cal Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-6
Empty Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-7
Usi ng Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-7
The expl ore Exampl e . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-7
API Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-8
The API Documentati on Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-8
API Tutori al Fi l es . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-8
How Thi s Book I s Organi zed . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-9
ii Contents
2
GettingStarted
IntroducingMEX-Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2
Usi ng MEX-Fi l es . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2
The Di sti ncti on Between mx and mex Prefi xes . . . . . . . . . . . . . 2-3
mx Routi nes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-3
mex Routi nes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-3
BuildingMEX-Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-4
Testi ng Your Confi gurati on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-4
On UNI X . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-5
On Wi ndows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-6
Usi ng f to Speci fy an Opti ons Fi l e . . . . . . . . . . . . . . . . . . . . . . . 2-8
Preconfi gured Opti ons Fi l es . . . . . . . . . . . . . . . . . . . . . . . . . . 2-9
TroubleshootingYour Configuration . . . . . . . . . . . . . . . . . . . . . 2-12
Search Path Probl em on Wi ndows . . . . . . . . . . . . . . . . . . . . 2-12
MATLAB Pathnames Contai ni ng Spaces on Wi ndows . . . . 2-12
DLLs Not on Path on Wi ndows . . . . . . . . . . . . . . . . . . . . . . . 2-12
Non-ANSI Compi l er on UNI X . . . . . . . . . . . . . . . . . . . . . . . . 2-12
General Confi gurati on Probl em . . . . . . . . . . . . . . . . . . . . . . 2-12
3
CreatingC LanguageMEX-Files
C MEX-Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-2
Di rectory Organi zati on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-2
The Parts of a MEX-Fi l e . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-2
Requi red Arguments to a MEX-Fi l e . . . . . . . . . . . . . . . . . . . . 3-5
Examples of C MEX-Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-7
A Fi rst Exampl e . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-7
Mani pul ati ng Stri ngs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-11
Passi ng Two or More I nputs or Outputs . . . . . . . . . . . . . . . . . . 3-14
Mani pul ati ng Structures and Cel l Arrays . . . . . . . . . . . . . . . . 3-16
Handl i ng Compl ex Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-20
iii
Handl i ng 8-,16-, and 32-Bi t Data . . . . . . . . . . . . . . . . . . . . . . . 3-23
Mani pul ati ng Mul ti di mensi onal Numeri cal Arrays . . . . . . . . 3-25
Handl i ng Sparse Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-29
Cal l i ng MATLAB Functi ons and Other User-Defi ned
Functi ons from Wi thi n a MEX-Fi l e . . . . . . . . . . . . . . . . . . . . . 3-33
Advanced Topics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-37
Hel p Fi l es . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-37
Li nki ng Mul ti pl e Fi l es . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-37
Vari abl e Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-37
Memory Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-38
Automati c Cl eanup of Temporary Arrays . . . . . . . . . . . . . . 3-38
Persi stent Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-38
Hybri d Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-40
Howto DebugC LanguageMEX-Files . . . . . . . . . . . . . . . . . . . . 3-41
Debuggi ng on UNI X . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-41
Debuggi ng on Wi ndows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-42
4
CreatingFortran MEX-Files
Fortran MEX-Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2
Di rectory Organi zati on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2
MEX-Fi l es and Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2
The Components of a Fortran MEX-Fi l e . . . . . . . . . . . . . . . . . . 4-2
The Poi nter Concept . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-5
The Gateway Routi ne . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-6
The %val Construct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-8
Examples of Fortran MEX-Files . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-9
A Fi rst Exampl e Passi ng a Scal ar . . . . . . . . . . . . . . . . . . . . . 4-9
Passi ng Stri ngs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-12
Passi ng Arrays of Stri ngs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-14
Passi ng Matri ces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-17
Passi ng Two or More I nputs or Outputs . . . . . . . . . . . . . . . . . . 4-19
Handl i ng Compl ex Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-22
iv Contents
Dynami c Al l ocati on of Memory . . . . . . . . . . . . . . . . . . . . . . . . . 4-26
Handl i ng Sparse Matri ces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-28
Cal l i ng MATLAB Functi ons from Fortran MEX-Fi l es . . . . . . 4-32
Advanced Topics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-36
Hel p Fi l es . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-36
Li nki ng Mul ti pl e Fi l es . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-36
Vari abl e Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-36
Memory Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-37
Howto DebugFortran LanguageMEX-Files . . . . . . . . . . . . . . 4-38
Debuggi ng on UNI X . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-38
Debuggi ng on Wi ndows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-39
5
Data Export and Import
UsingMAT-Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-2
I mporti ng Data to MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-2
Exporti ng Data from MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . 5-3
Exchangi ng Data Fi l es Between Pl atforms . . . . . . . . . . . . . . . . 5-4
Readi ng and Wri ti ng MAT-Fi l es . . . . . . . . . . . . . . . . . . . . . . . . . 5-4
MAT-Fi l e I nterface Li brary . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-5
Di rectory Organi zati on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-7
Wi ndows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-8
UNI X . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-8
Exampl e Fi l es . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-9
Examples of MAT-Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-10
Creati ng a MAT-Fi l e . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-10
C Exampl e . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-10
Fortran Exampl e . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-14
Readi ng a MAT-Fi l e . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-19
C Exampl e . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-19
Fortran Exampl e . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-24
v
Compilingand LinkingMAT-FilePrograms . . . . . . . . . . . . . . 5-28
Speci al Consi derati ons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-28
Fl oati ng-Poi nt Excepti ons . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-28
UNI X . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-29
Setti ng Runti me Li brary Path . . . . . . . . . . . . . . . . . . . . . . . 5-29
Compi l i ng and Li nki ng Commands . . . . . . . . . . . . . . . . . . . 5-30
Speci al Consi derati on for Fortran (f77) on HP-UX 10.x . . . 5-31
Wi ndows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-31
6
UsingtheMATLAB Engine
Interprocess Communication: TheMATLAB Engine. . . . . . . 6-2
The Engi ne Li brary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-3
Communi cati ng wi th MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . 6-4
Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-5
Cal l i ng the MATLAB Engi ne . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-5
C Exampl e . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-5
Fortran Exampl e . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-10
Compilingand LinkingEnginePrograms . . . . . . . . . . . . . . . . 6-14
Speci al Consi derati ons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-14
Fl oati ng-Poi nt Excepti ons . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-14
UNI X . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-16
Setti ng Runti me Li brary Path . . . . . . . . . . . . . . . . . . . . . . . 6-16
Compi l i ng and Li nki ng Commands . . . . . . . . . . . . . . . . . . . 6-16
Speci al Consi derati on for Fortran (f77) on HP-UX 10.x . . . 6-17
Wi ndows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-18
vi Contents
7
Client/Server Applications
MATLAB ActiveX Integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-2
What I s Acti veX? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-2
Acti veX Concepts and Termi nol ogy . . . . . . . . . . . . . . . . . . . . 7-2
MATLAB Acti veX Support Overvi ew . . . . . . . . . . . . . . . . . . . 7-3
MATLAB Acti veX Cl i ent Support . . . . . . . . . . . . . . . . . . . . . . . . 7-4
Usi ng Acti veX Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-4
Acti veX Cl i ent Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-5
Wri ti ng Event Handl ers . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-21
Addi ti onal Acti veX Cl i ent I nformati on . . . . . . . . . . . . . . . . . . . 7-23
Rel easi ng I nterfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-23
Usi ng Acti veX Col l ecti ons . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-23
Data Conversi ons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-24
Usi ng MATLAB As a DCOM Server Cl i ent . . . . . . . . . . . . . 7-25
MATLAB Acti veX Control Contai ner Li mi tati ons . . . . . . . . 7-26
MATLAB Sampl e Control . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-26
MATLAB Acti veX Automati on Server Support . . . . . . . . . . . . 7-26
MATLAB Acti veX Automati on Methods . . . . . . . . . . . . . . . 7-27
Addi ti onal Acti veX Server I nformati on . . . . . . . . . . . . . . . . . . 7-30
Launchi ng the MATLAB Acti veX Server . . . . . . . . . . . . . . . 7-30
Speci fyi ng a Shared or Dedi cated Server . . . . . . . . . . . . . . . 7-30
Usi ng MATLAB As a DCOM Server . . . . . . . . . . . . . . . . . . . 7-31
Dynamic Data Exchange(DDE) . . . . . . . . . . . . . . . . . . . . . . . . . . 7-32
DDE Concepts and Termi nol ogy . . . . . . . . . . . . . . . . . . . . . . . . 7-32
The Servi ce Name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-33
The Topi c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-33
The I tem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-33
Cl i pboard Formats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-33
Accessi ng MATLAB As a Server . . . . . . . . . . . . . . . . . . . . . . . . 7-34
The DDE Name Hi erarchy . . . . . . . . . . . . . . . . . . . . . . . . . . 7-35
MATLAB DDE Topi cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-35
Exampl e: Usi ng Vi sual Basi c and
the MATLAB DDE Server . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-38
Usi ng MATLAB As a Cl i ent . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-39
DDE Advi sory Li nks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-41
vii
8
SystemSetup
CustomBuildingMEX-Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-2
Locati ng the Defaul t Opti ons Fi l e . . . . . . . . . . . . . . . . . . . . . 8-4
UNI X . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-5
Wi ndows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-7
Li nki ng DLLs to MEX-Fi l es . . . . . . . . . . . . . . . . . . . . . . . . . . 8-9
Versi oni ng MEX-Fi l es . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-9
Compi l i ng MEX-Fi l es wi th
the Mi crosoft Vi sual C++ I DE . . . . . . . . . . . . . . . . . . . . . . . . . 8-9
Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-11
MEX-Fi l e Creati on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-11
Understandi ng MEX-Fi l e Probl ems . . . . . . . . . . . . . . . . . . . . . 8-12
MEX-Fi l es Created i n Watcom I DE . . . . . . . . . . . . . . . . . . . 8-15
so_l ocati ons Error on SGI . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-16
Memory Management Compati bi l i ty I ssues . . . . . . . . . . . . . . . 8-16
I mproperl y Destroyi ng an mxArray . . . . . . . . . . . . . . . . . . . 8-16
I ncorrectl y Constructi ng a Cel l or Structure mxArray . . . . 8-17
Creati ng a Temporary mxArray wi th I mproper Data . . . . . 8-18
Potenti al Memory Leaks . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-19
MEX-Fi l es Shoul d Destroy
Thei r Own Temporary Arrays . . . . . . . . . . . . . . . . . . . . . . . . 8-20
A
API Functions
C MX-Functi ons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-2
C MEX-Functi ons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-4
C MAT-Fi l e Routi nes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-5
C Engi ne Routi nes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-6
Fortran MX-Functi ons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-6
Fortran MEX-Functi ons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-7
Fortran MAT-Fi l e Routi nes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-8
Fortran Engi ne Routi nes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-8
DDE Routi nes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-9
viii Contents
B
Directory Organization
Directory Organization on UNIX . . . . . . . . . . . . . . . . . . . . . . . . . . B-3
Directory Organization on Windows . . . . . . . . . . . . . . . . . . . . . . B-7
1
I ntroduci ng the
MATLAB API
Introduction to MATLAB API . . . . . . . . . . . . 1-2
MEX-Fi l es . . . . . . . . . . . . . . . . . . . . . 1-2
MAT-Fi l e Appl i cati ons . . . . . . . . . . . . . . . . 1-2
Engi ne Appl i cati ons . . . . . . . . . . . . . . . . . 1-3
MATLAB Data . . . . . . . . . . . . . . . . . . . 1-4
The MATLAB Array . . . . . . . . . . . . . . . . . 1-4
Data Storage . . . . . . . . . . . . . . . . . . . . 1-4
Data Types i n MATLAB . . . . . . . . . . . . . . . . 1-5
Usi ng Data Types . . . . . . . . . . . . . . . . . . 1-7
API Documentation . . . . . . . . . . . . . . . . . 1-8
The API Documentati on Set . . . . . . . . . . . . . . 1-8
How Thi s Book I s Organi zed . . . . . . . . . . . . . . 1-9
1 Introducing the MATLAB API
1-2
Introduction to MATLAB API
Al though MATLAB
Z
Examples of C MEX-Files
3-7
Examples of C MEX-Files
The next secti ons of thi s chapter i ncl ude exampl es of di fferent MEX-fi l es. The
MATLAB 5 API provi des a ful l set of routi nes that handl e the vari ous data
types supported by MATLAB. For each data type there i s a speci fi c set of
functi ons that you can use for data mani pul ati on. The fi rst exampl e di scusses
the si mpl e case of doubl i ng a scal ar. After that, the exampl es di scuss how to
pass i n, mani pul ate, and pass back vari ous data types, and how to handl e
mul ti pl e i nputs and outputs. Fi nal l y, the secti ons di scuss passi ng and
mani pul ati ng vari ous MATLAB data types.
Note: You can fi nd the most recent versi ons of the exampl e programs from
thi s chapter at the anonymous FTP server:
ftp.mathworks.com/pub/tech-support/library/matlab5/extern/examples/refbook
A First Example
Lets l ook at a si mpl e exampl e of C code and i ts MEX-fi l e equi val ent. Here i s a
C computati onal functi on that takes a scal ar and doubl es i t.
#include <math.h>
void timestwo(double y[], double x[])
{
y[0] = 2.0*x[0];
return;
}
3 Creating C Language MEX-Files
3-8
Bel ow i s the same functi on wri tten i n the MEX-fi l e format.
#include "mex.h"
/*
* timestwo.c - example found in API guide
*
* Computational function that takes a scalar and doubles it.
*
* This is a MEX-file for MATLAB.
* Copyright (c) 1984-1998 The MathWorks, Inc.
*/
/* $Revision: 1.5 $ */
void timestwo(double y[], double x[])
{
y[0] = 2.0*x[0];
}
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[] )
{
double *x,*y;
int mrows,ncols;
/* Check for proper number of arguments. */
if(nrhs!=1) {
mexErrMsgTxt("One input required.");
} else if(nlhs>1) {
mexErrMsgTxt("Too many output arguments");
}
/* The input must be a noncomplex scalar double.*/
mrows = mxGetM(prhs[0]);
ncols = mxGetN(prhs[0]);
if( !mxIsDouble(prhs[0]) || mxIsComplex(prhs[0]) ||
!(mrows==1 && ncols==1) ) {
mexErrMsgTxt("Input must be a noncomplex scalar double.");
}
Examples of C MEX-Files
3-9
/* Create matrix for the return argument. */
plhs[0] = mxCreateDoubleMatrix(mrows,ncols, mxREAL);
/* Assign pointers to each input and output. */
x = mxGetPr(prhs[0]);
y = mxGetPr(plhs[0]);
/* Call the timestwo subroutine. */
timestwo(y,x);
}
I n C, functi on argument checki ng i s done at compi l e ti me. I n MATLAB, you can
pass any number or type of arguments to your M-functi on, whi ch i s responsi bl e
for argument checki ng. Thi s i s al so true for MEX-fi l es. Your program must
safel y handl e any number of i nput or output arguments of any supported type.
To compi l e and l i nk thi s exampl e source fi l e at the MATLAB prompt, type
mex timestwo.c
Thi s carri es out the necessary steps to create the MEX-fi l e cal l ed timestwo
wi th an extensi on correspondi ng to the pl atform on whi ch youre runni ng. You
can now cal l timestwo as i f i t were an M-functi on.
x = 2;
y = timestwo(x)
y =
4
You can create and compi l e MEX-fi l es i n MATLAB or at your operati ng
systems prompt. MATLAB uses mex.m, an M-fi l e versi on of the mex scri pt, and
your operati ng system uses mex.bat on Wi ndows and mex.sh on UNI X. I n
ei ther case, typi ng
mex filename
at the prompt produces a compi l ed versi on of your MEX-fi l e.
I n the above exampl e, scal ars are vi ewed as 1-by-1 matri ces. Al ternati vel y, you
can use a speci al API functi on cal l ed mxGetScalar that returns the val ues of
3 Creating C Language MEX-Files
3-10
scal ars i nstead of poi nters to copi es of scal ar vari abl es. Thi s i s the al ternati ve
code (error checki ng has been omi tted for brevi ty).
#include "mex.h"
/*
* timestwoalt.c - example found in API guide
*
* Use mxGetScalar to return the values of scalars instead of
* pointers to copies of scalar variables.
*
* This is a MEX-file for MATLAB.
* Copyright (c) 1984-1998 The MathWorks, Inc.
*/
/* $Revision: 1.2 $ */
void timestwo_alt(double *y, double x)
{
*y = 2.0*x;
}
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[] )
{
double *y;
double x;
/* Create a 1-by-1 matrix for the return argument. */
plhs[0] = mxCreateDoubleMatrix(1,1,mxREAL);
/* Get the scalar value of the input x. */
/* Note: mxGetScalar returns a value, not a pointer. */
x = mxGetScalar(prhs[0]);
/* Assign a pointer to the output. */
y = mxGetPr(plhs[0]);
/* Call the timestwo_alt subroutine. */
timestwo_alt(y,x);
}
Examples of C MEX-Files
3-11
Thi s exampl e passes the i nput scal ar x by val ue i nto the timestwo_alt
subrouti ne, but passes the output scal ar y by reference.
Manipulating Strings
Any MATLAB data type can be passed to and from MEX-fi l es. For exampl e,
thi s C code accepts a stri ng and returns the characters i n reverse order.
/* $Revision: 1.7 $ */
/*=============================================================
* revord.c
* Example for illustrating how to copy the string data from
* MATLAB to a C-style string and back again.
*
* Takes a string and returns a string in reverse order.
*
* This is a MEX-file for MATLAB.
* Copyright (c) 1984-1998 The MathWorks, Inc.
*============================================================*/
#include "mex.h"
void revord(char *input_buf, int buflen, char *output_buf)
{
int i;
/* Reverse the order of the input string. */
for(i=0;i<buflen1;i++)
*(output_buf+i) = *(input_buf+bufleni2);
}
I n thi s exampl e, the API functi on mxCalloc repl aces calloc, the standard C
functi on for dynami c memory al l ocati on. mxCalloc al l ocates dynami c memory
usi ng MATLABs memory manager and i ni ti al i zes i t to zero. You must use
mxCalloc i n any si tuati on where C woul d requi re the use of calloc. The same
i s true for mxMalloc and mxRealloc; use mxMalloc i n any si tuati on where C
3 Creating C Language MEX-Files
3-12
woul d requi re the use of malloc and use mxRealloc where C woul d requi re
realloc.
Note: MATLAB automati cal l y frees up memory al l ocated wi th the mx
al l ocati on routi nes (mxCalloc, mxMalloc, mxRealloc) upon exi ti ng your
MEX-fi l e. I f you dont want thi s to happen, use the API functi on
mexMakeMemoryPersistent.
Bel ow i s the gateway functi on that cal l s the C computati onal routi ne revord.
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
char *input_buf, *output_buf;
int buflen,status;
/* Check for proper number of arguments. */
if(nrhs!=1)
mexErrMsgTxt("One input required.");
else if(nlhs > 1)
mexErrMsgTxt("Too many output arguments.");
/* Input must be a string. */
if ( mxIsChar(prhs[0]) != 1)
mexErrMsgTxt("Input must be a string.");
/* Input must be a row vector. */
if (mxGetM(prhs[0])!=1)
mexErrMsgTxt("Input must be a row vector.");
/* Get the length of the input string. */
buflen = (mxGetM(prhs[0]) * mxGetN(prhs[0])) + 1;
/* Allocate memory for input and output strings. */
input_buf=mxCalloc(buflen, sizeof(char));
output_buf=mxCalloc(buflen, sizeof(char));
Examples of C MEX-Files
3-13
/* Copy the string data from prhs[0] into a C string
* input_ buf.
* If the string array contains several rows, they are copied,
* one column at a time, into one long string array.
*/
status = mxGetString(prhs[0], input_buf, buflen);
if(status != 0)
mexWarnMsgTxt("Not enough space. String is truncated.");
/* Call the C subroutine. */
revord(input_buf, buflen, output_buf);
/* Set C-style string output_buf to MATLAB mexFunction
output*/
plhs[0] = mxCreateString(output_buf);
return;
}
The gateway functi on al l ocates memory for the i nput and output stri ngs. Si nce
these are C stri ngs, they need to be one greater than the number of el ements
i n the MATLAB stri ng. Next the MATLAB stri ng i s copi ed to the i nput stri ng.
Both the i nput and output stri ngs are passed to the computati onal subrouti ne
(revord), whi ch l oads the output i n reverse order. Note that the output buffer
i s a val i d nul l -termi nated C stri ng because mxCalloc i ni ti al i zes the memor y to
0. The API functi on mxCreateString then creates a MATLAB stri ng from the
C stri ng, output_buf. Fi nal l y, plhs[0], the l eft-hand si de return argument to
MATLAB, i s set to the MATLAB array you just created.
By i sol ati ng vari abl es of type mxArray from the computati onal subrouti ne, you
can avoi d havi ng to make si gni fi cant changes to your ori gi nal C code.
I n thi s exampl e, typi ng
x = 'hello world';
y = revord(x)
produces
The string to convert is 'hello world'.
y =
dlrow olleh
3 Creating C Language MEX-Files
3-14
Passing Two or More Inputs or Outputs
The plhs[] and prhs[] parameters are vectors that contai n poi nters to each
l eft-hand si de (output) vari abl e and each ri ght-hand si de (i nput) vari abl e,
respecti vel y. Accordi ngl y, plhs[0] contai ns a poi nter to the fi rst l eft-hand si de
argument, plhs[1] contai ns a poi nter to the second l eft-hand si de argument,
and so on. Li kewi se, prhs[0] contai ns a poi nter to the fi rst ri ght-hand si de
argument, prhs[1] poi nts to the second, and so on.
Thi s exampl e, xtimesy, mul ti pl i es an i nput scal ar by an i nput scal ar or matri x
and outputs a matri x. For exampl e, usi ng xtimesy wi th two scal ars gi ves
x = 7;
y = 7;
z = xtimesy(x,y)
z =
49
Usi ng xtimesy wi th a scal ar and a matri x gi ves
x = 9;
y = ones(3);
z = xtimesy(x,y)
z =
9 9 9
9 9 9
9 9 9
Thi s i s the correspondi ng MEX-fi l e C code.
#include "mex.h"
/*
* xtimesy.c - example found in API guide
*
* Multiplies an input scalar times an input matrix and outputs a
* matrix
*
* This is a MEX-file for MATLAB.
* Copyright (c) 1984-1998 The MathWorks, Inc.
*/
Examples of C MEX-Files
3-15
/* $Revision: 1.5 $ */
void xtimesy(double x, double *y, double *z, int m, int n)
{
int i,j,count=0;
for (i=0; i<n; i++) {
for (j=0; j<m; j++) {
*(z+count) = x * *(y+count);
count++;
}
}
}
/* The gateway function */
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
double *y,*z;
double x;
int status,mrows,ncols;
/* Check for proper number of arguments. */
if(nrhs!=2)
mexErrMsgTxt("Two inputs required.");
if(nlhs!=1)
mexErrMsgTxt("One output required.");
/* Check to make sure the first input argument is a scalar. */
if( !mxIsNumeric(prhs[0]) || !mxIsDouble(prhs[0]) ||
mxIsEmpty(prhs[0]) || mxIsComplex(prhs[0]) ||
mxGetN(prhs[0])*mxGetM(prhs[0])!=1 ) {
mexErrMsgTxt("Input x must be a scalar.");
}
/* Get the scalar input x. */
x = mxGetScalar(prhs[0]);
3 Creating C Language MEX-Files
3-16
/* Create a pointer to the input matrix y. */
y = mxGetPr(prhs[1]);
/* Get the dimensions of the matrix input y. */
mrows = mxGetM(prhs[1]);
ncols = mxGetN(prhs[1]);
/* Set the output pointer to the output matrix. */
plhs[0] = mxCreateDoubleMatrix(mrows,ncols, mxREAL);
/* Create a C pointer to a copy of the output matrix. */
z = mxGetPr(plhs[0]);
/* Call the C subroutine. */
xtimesy(x,y,z,mrows,ncols);
}
As thi s exampl e shows, creati ng MEX-fi l e gateways that handl e mul ti pl e
i nputs and outputs i s strai ghtforward. Al l you need to do i s keep track of whi ch
i ndi ces of the vectors prhs and plhs correspond to the i nput and output
arguments of your functi on. I n the exampl e above, the i nput vari abl e x
corresponds to prhs[0] and the i nput vari abl e y to prhs[1].
Note that mxGetScalar returns the val ue of x r ather than a poi nter to x. Thi s
i s just an al ternati ve way of handl i ng scal ars. You coul d treat x as a 1-by-1
matri x and use mxGetPr to return a poi nter to x.
Manipulating Structures and Cell Arrays
Structures and cel l arrays are new data types i n MATLAB 5; for a di scussi on
of the features of structures and cel l arrays and the bui l t-i n functi ons MATLAB
provi des for mani pul ati ng them, refer to UsingMATLAB. Li ke al l other data
types i n MATLAB, structures and cel l arrays can be passed i nto and out of C
MEX-fi l es.
Passi ng structures and cel l arrays i nto MEX-fi l es i s just l i ke passi ng any other
data types, except the data i tsel f i s of type mxArray. I n practi ce, thi s means that
mxGetField (for structures) and mxGetCell (for cel l arrays) return poi nters of
type mxArray. You can then treat the poi nters l i ke any other poi nters of type
Examples of C MEX-Files
3-17
mxArray, but i f you want to pass the data contai ned i n the mxArray to a C
routi ne, you must use an API functi on such as mxGetData to access i t.
Thi s exampl e takes an m-by-n structure matri x as i nput and returns a new
1-by-1 structure that contai ns these fi el ds:
Stri ng i nput generates an m-by-n cel l array
Numeri c i nput (noncompl ex, scal ar val ues) generates an m-by-n vector of
numbers wi th the same cl ass I D as the i nput, for exampl e int, double, and
so on.
/* $Revision: 1.1 $ */
/*
===============================================================
* phonebook.c
* Example for illustrating how to manipulate structure and cell
* arrays
* Takes an (MxN) structure matrix and returns a new structure
* (1-by-1) containing corresponding fields: for string input, it
* will be (MxN) cell array; and for numeric (noncomplex, scalar)
* input, it will be (MxN) vector of numbers with the same classID
* as input, such as int, double, etc..
*
* This is a MEX-file for MATLAB.
* Copyright (c) 1984-1998 The MathWorks, Inc.
*============================================================*/
#include "mex.h"
#include "string.h"
#define MAXCHARS 80 /* max length of string contained in each
field */
/* The gateway routine */
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[] )
{
3 Creating C Language MEX-Files
3-18
const char **fnames; /* Pointers to field names */
const int *dims;
mxArray *tmp, *fout;
char *pdata;
int ifield, jstruct, *classIDflags;
int NStructElems, nfields, ndim;
/* Check proper input and output. */
if(nrhs!=1)
mexErrMsgTxt("One input required.");
else if(nlhs > 1)
mexErrMsgTxt("Too many output arguments.");
else if(!mxIsStruct(prhs[0]))
mexErrMsgTxt("Input must be a structure.");
/* Get input arguments. */
nfields = mxGetNumberOfFields(prhs[0]);
NStructElems = mxGetNumberOfElements(prhs[0]);
/* Allocate memory for storing classIDflags. */
classIDflags = mxCalloc(nfields, sizeof(int));
/* Check empty field, proper data type, and data type
consistency; and get classID for each field. */
for(ifield=0; ifield<nfields; ifield++) {
for(jstruct = 0; jstruct < NStructElems; jstruct++) {
tmp = mxGetFieldByNumber(prhs[0], jstruct, ifield);
if(tmp == NULL) {
mexPrintf("%s%d\t%s%d\n", "FIELD: ", ifield+1, "STRUCT
INDEX :", jstruct+1);
mexErrMsgTxt("Above field is empty!");
}
if(jstruct==0) {
if( !mxIsChar(tmp) && !mxIsNumeric(tmp)) {
mexPrintf("%s%d\t%s%d\n", "FIELD: ", ifield+1, "STRUCT
INDEX :", jstruct+1);
mexErrMsgTxt("Above field must have either string or
numeric data.");
}
classIDflags[ifield]=mxGetClassID(tmp);
} else {
Examples of C MEX-Files
3-19
if (mxGetClassID(tmp) != classIDflags[ifield]) {
mexPrintf("%s%d\t%s%d\n", "FIELD: ", ifield+1,
"STRUCT INDEX :", jstruct+1);
mexErrMsgTxt("Inconsistent data type in above field!");
} else if(!mxIsChar(tmp) &&
((mxIsComplex(tmp) || mxGetNumberOfElements(tmp)!=1))){
mexPrintf("%s%d\t%s%d\n", "FIELD: ", ifield+1,
"STRUCT INDEX :", jstruct+1);
mexErrMsgTxt("Numeric data in above field must be scalar
and noncomplex!");
}
}
}
}
/* Allocate memory for storing pointers. */
fnames = mxCalloc(nfields, sizeof(*fnames));
/* Get field name pointers. */
for (ifield=0; ifield< nfields; ifield++){
fnames[ifield] = mxGetFieldNameByNumber(prhs[0],ifield);
}
/* Create a 1x1 struct matrix for output. */
plhs[0] = mxCreateStructMatrix(1, 1, nfields, fnames);
mxFree(fnames);
ndim = mxGetNumberOfDimensions(prhs[0]);
dims = mxGetDimensions(prhs[0]);
for(ifield=0; ifield<nfields; ifield++) {
/* Create cell/numeric array. */
if(classIDflags[ifield] == mxCHAR_CLASS) {
fout = mxCreateCellArray(ndim, dims);
}else {
fout = mxCreateNumericArray(ndim, dims,
classIDflags[ifield], mxREAL);
pdata = mxGetData(fout);
}
/* Copy data from input structure array. */
for (jstruct=0; jstruct<NStructElems; jstruct++) {
tmp = mxGetFieldByNumber(prhs[0],jstruct,ifield);
if( mxIsChar(tmp)) {
mxSetCell(fout, jstruct, mxDuplicateArray(tmp));
3 Creating C Language MEX-Files
3-20
}else {
size_t sizebuf;
sizebuf = mxGetElementSize(tmp);
memcpy(pdata, mxGetData(tmp), sizebuf);
pdata += sizebuf;
}
}
/* Set each field in output structure. */
mxSetFieldByNumber(plhs[0], 0, ifield, fout);
}
mxFree(classIDflags);
return;
To see how thi s program works, enter thi s structure.
friends(1).name = 'Jordan Robert';
friends(1).phone = 3386;
friends(2).name = 'Mary Smith';
friends(2).phone = 3912;
friends(3).name = 'Stacy Flora';
friends(3).phone = 3238;
friends(4).name = 'Harry Alpert';
friends(4).phone = 3077;
The resul ts of thi s i nput are
phonebook(friends)
ans =
name: {1x4 cell }
phone: [3386 3912 3238 3077]
Handling Complex Data
Compl ex data from MATLAB i s separated i nto real and i magi nary parts.
MATLABs API provi des two functi ons, mxGetPr and mxGetPi, that return
poi nters (of type double *) to the real and i magi nary parts of your data.
Examples of C MEX-Files
3-21
Thi s exampl e takes two compl ex r ow vector s and convol ves them.
/* $Revision: 1.5 $ */
/*=========================================================
* convec.c
* Example for illustrating how to pass complex data
* from MATLAB to C and back again
*
* Convolves two complex input vectors.
*
* This is a MEX-file for MATLAB.
* Copyright (c) 1984-1998 The MathWorks, Inc.
*=======================================================*/
#include "mex.h"
/* Computational subroutine */
void convec( double *xr, double *xi, int nx,
double *yr, double *yi, int ny,
double *zr, double *zi)
{
int i,j;
zr[0]=0.0;
zi[0]=0.0;
/* Perform the convolution of the complex vectors. */
for(i=0; i<nx; i++) {
for(j=0; j<ny; j++) {
*(zr+i+j) = *(zr+i+j) + *(xr+i) * *(yr+j) *(xi+i)
* *(yi+j);
*(zi+i+j) = *(zi+i+j) + *(xr+i) * *(yi+j) + *(xi+i)
* *(yr+j);
}
}
}
3 Creating C Language MEX-Files
3-22
Bel ow i s the gateway functi on that cal l s thi s compl ex convol uti on.
/* The gateway routine. */
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[] )
{
double *xr, *xi, *yr, *yi, *zr, *zi;
int rows, cols, nx, ny;
/* Check for the proper number of arguments. */
if(nrhs != 2)
mexErrMsgTxt("Two inputs required.");
if(nlhs > 1)
mexErrMsgTxt("Too many output arguments.");
/* Check that both inputs are row vectors. */
if( mxGetM(prhs[0]) != 1 || mxGetM(prhs[1]) != 1 )
mexErrMsgTxt("Both inputs must be row vectors.");
rows = 1;
/* Check that both inputs are complex. */
if( !mxIsComplex(prhs[0]) || !mxIsComplex(prhs[1]) )
mexErrMsgTxt("Inputs must be complex.\n");
/* Get the length of each input vector. */
nx = mxGetN(prhs[0]);
ny = mxGetN(prhs[1]);
/* Get pointers to real and imaginary parts of the inputs. */
xr = mxGetPr(prhs[0]);
xi = mxGetPi(prhs[0]);
yr = mxGetPr(prhs[1]);
yi = mxGetPi(prhs[1]);
/* Create a new array and set the output pointer to it. */
cols = nx + ny 1;
plhs[0] = mxCreateDoubleMatrix(rows, cols, mxCOMPLEX);
zr = mxGetPr(plhs[0]);
zi = mxGetPi(plhs[0]);
Examples of C MEX-Files
3-23
/* Call the C subroutine. */
convec(xr, xi, nx, yr, yi, ny, zr, zi);
return;
}
Enteri ng these numbers at the MATLAB prompt
x = [3.000 1.000i, 4.000 + 2.000i, 7.000 3.000i];
y = [8.000 6.000i, 12.000 + 16.000i, 40.000 42.000i];
and i nvoki ng the new MEX-fi l e
z = convec(x,y)
resul ts i n
z =
1.0e+02 *
Columns 1 through 4
0.1800 0.2600i 0.9600 + 0.2800i 1.3200 1.4400i 3.7600 0.1200i
Column 5
1.5400 4.1400i
whi ch agrees wi th the resul ts that the bui l t-i n MATLAB functi on conv.m
produces.
Handling 8-,16-, and 32-Bit Data
You can create and mani pul ate si gned and unsi gned 8-, 16-, and 32-bi t data
from wi thi n your MEX-fi l es. The MATLAB 5 API provi des a set of functi ons
that support these data types. The API functi on mxCreateNumericArray
constructs an unpopul ated N-di mensi onal numeri c array wi th a speci fi ed data
si ze. Refer to the entry for mxClassID i n the onl i ne reference pages for a
di scussi on of how the MATLAB 5 API represents these data types.
Once you have created an unpopul ated MATLAB array of a speci fi ed data type,
you can access the data usi ng mxGetData and mxGetImagData. These two
functi ons return poi nters to the real and i magi nary data. You can perform
3 Creating C Language MEX-Files
3-24
ari thmeti c on data of 8-, 16- or 32-bi t preci si on i n MEX-fi l es and return the
resul t to MATLAB, whi ch wi l l recogni ze the correct data cl ass. Al though from
wi thi n MATLAB i t i s not currentl y possi bl e to perform ari thmeti c or to cal l
MATLAB functi ons that perform data mani pul ati on on data of 8-, 16-, or 32-bi t
preci si on, you can di spl ay the data at the MATLAB prompt and save i t i n a
MAT-fi l e.
Thi s exampl e constructs a 2-by-2 matri x wi th unsi gned 16-bi t i ntegers, doubl es
each el ement, and returns both matri ces to MATLAB.
#include <string.h> /* Needed for memcpy() */
#include "mex.h"
/*
* doubleelement.c - Example found in API Guide
*
* Constructs a 2-by-2 matrix with unsigned 16-bit integers,
* doubles each element, and returns the matrix.
*
* This is a MEX-file for MATLAB.
* Copyright (c) 1984-1998 The MathWorks, Inc.
*/
/* $Revision: 1.4 $ */
#define NDIMS 2
#define TOTAL_ELEMENTS 4
/* The computational subroutine */
void dbl_elem(unsigned short *x)
{
unsigned short scalar=2;
int i,j;
for(i=0;i<2;i++) {
for(j=0;j<2;j++) {
*(x+i+j) = scalar * *(x+i+j);
}
}
}
Examples of C MEX-Files
3-25
/* The gataway function */
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[] )
{
const int dims[]={2,2};
unsigned char *start_of_pr;
unsigned short data[]={1,2,3,4};
int bytes_to_copy;
/* Call the computational subroutine. */
dbl_elem(data);
/* Create a 2-by-2 array of unsigned 16-bit integers. */
plhs[0] = mxCreateNumericArray(NDIMS,dims,
mxUINT16_CLASS,mxREAL);
/* Populate the real part of the created array. */
start_of_pr = (unsigned char *)mxGetPr(plhs[0]);
bytes_to_copy = TOTAL_ELEMENTS * mxGetElementSize(plhs[0]);
memcpy(start_of_pr,data,bytes_to_copy);
}
At the MATLAB prompt, enteri ng
doubleelement
produces
ans =
2 6
8 4
The output of thi s functi on i s a 2-by-2 matri x popul ated wi th unsi gned 16-bi t
i ntegers. You can vi ew the contents of thi s matri x i n MATLAB, but you cannot
mani pul ate the data i n any fashi on.
Manipulating Multidimensional Numerical Arrays
Mul ti di mensi onal numeri cal arrays are a new data type i n MATLAB 5. For a
di scussi on of the features of mul ti di mensi onal numeri cal arrays and the
bui l t-i n functi ons MATLAB provi des to mani pul ate them, refer to Using
MATLAB. Li ke al l other data types i n MATLAB, arrays can be passed i nto and
3 Creating C Language MEX-Files
3-26
out of MEX-fi l es wri tten i n C. You can mani pul ate mul ti di mensi onal numeri cal
arrays by usi ng mxGetData and mxGetImagData to return poi nters to the real
and i magi nary parts of the data stored i n the ori gi nal mul ti di mensi onal array.
Thi s exampl e takes an N-di mensi onal array of doubl es and returns the i ndi ces
for the nonzero el ements i n the array.
/*=============================================================
* findnz.c
* Example for illustrating how to handle N-dimensional arrays in
* a MEX-file. NOTE: MATLAB uses 1-based indexing, C uses 0-based
* indexing.
*
* Takes an N-dimensional array of doubles and returns the indices
* for the non-zero elements in the array. findnz works
* differently than the FIND command in MATLAB in that it returns
* all the indices in one output variable, where the column
* element contains the index for that dimension.
*
*
* This is a MEX-file for MATLAB.
* Copyright (c) 1984-98 by The MathWorks, Inc.
* All Rights Reserved.
*============================================================*/
/* $Revision: 1.2 $ */
#include "mex.h"
/* If you are using a compiler that equates NaN to zero, you must
* compile this example using the flag DNAN_EQUALS_ZERO. For
* example:
*
* mex DNAN_EQUALS_ZERO findnz.c
*
* This will correctly define the IsNonZero macro for your
compiler. */
Examples of C MEX-Files
3-27
#if NAN_EQUALS_ZERO
#define IsNonZero(d) ((d)!=0.0 || mxIsNaN(d))
#else
#define IsNonZero(d) ((d)!=0.0)
#endif
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
/* Declare variables. */
int elements, j, number_of_dims, cmplx;
int nnz=0, count=0;
double *pr, *pi, *pind;
const int *dim_array;
/* Check for proper number of input and output arguments. */
if (nrhs != 1) {
mexErrMsgTxt("One input argument required.");
}
if (nlhs > 1){
mexErrMsgTxt("Too many output arguments.");
}
/* Check data type of input argument. */
if (!(mxIsDouble(prhs[0]))) {
mexErrMsgTxt("Input array must be of type double.");
}
/* Get the number of elements in the input argument. */
elements = mxGetNumberOfElements(prhs[0]);
/* Get the data. */
pr = (double *)mxGetPr(prhs[0]);
pi = (double *)mxGetPi(prhs[0]);
cmplx = ((pi==NULL) ? 0 : 1);
3 Creating C Language MEX-Files
3-28
/* Count the number of non-zero elements to be able to allocate
the correct size for output variable. */
for(j=0;j<elements;j++){
if(IsNonZero(pr[j]) || (cmplx && IsNonZero(pi[j]))) {
nnz++;
}
}
/* Get the number of dimensions in the input argument.
Allocate the space for the return argument */
number_of_dims = mxGetNumberOfDimensions(prhs[0]);
plhs[0] = mxCreateDoubleMatrix(nnz, number_of_dims, mxREAL);
pind = mxGetPr(plhs[0]);
/* Get the number of dimensions in the input argument. */
dim_array = mxGetDimensions(prhs[0]);
/* Fill in the indices to return to MATLAB. This loops through the
* elements and checks for non-zero values. If it finds a non-zero
* value, it then calculates the corresponding MATLAB indices and
* assigns them into the output array. The 1 is added to the
* calculated index because MATLAB is 1-based and C is 0-based. */
for(j=0;j<elements;j++) {
if(IsNonZero(pr[j]) || (cmplx && IsNonZero(pi[j]))) {
int temp=j;
int k;
for (k=0;k<number_of_dims;k++){
pind[nnz*k+count]=((temp % (dim_array[k])) +1);
temp/=dim_array[k];
}
count++;
}
}
}
Examples of C MEX-Files
3-29
Enteri ng a sampl e matri x at the MATLAB prompt gi ves
matrix = [ 3 0 9 0; 0 8 2 4; 0 9 2 4; 3 0 9 3; 9 9 2 0]
matrix =
3 0 9 0
0 8 2 4
0 9 2 4
3 0 9 3
9 9 2 0
Thi s exampl e determi nes the posi ti on of al l nonzer o el ements i n the matr i x.
Runni ng the MEX-fi l e on thi s matri x produces
nz=findnz(matrix)
nz =
1 1
4 1
5 1
2 2
3 2
5 2
1 3
2 3
3 3
4 3
5 3
2 4
3 4
4 4
Handling Sparse Arrays
The MATLAB 5 API provi des a set of functi ons that al l ow you to create and
mani pul ate sparse arrays from wi thi n your MEX-fi l es. These API routi nes
access and mani pul ate ir and jc, two of the par ameter s associ ated wi th sparse
arrays. For more i nformati on on how MATLAB stores sparse arrays, refer to
The MATLAB Array secti on i n Chapter 1 of thi s gui de.
3 Creating C Language MEX-Files
3-30
Thi s exampl e i l l ustrates how to popul ate a sparse matri x.
/*=============================================================
* fulltosparse.c
* This example demonstrates how to populate a sparse
* matrix. For the purpose of this example, you must pass in a
* nonsparse, 2-dimensional argument of type double.
* Comment: You might want to modify this MEX-file so that you can
* use it to read large sparse data sets into MATLAB.
*
* This is a MEX-file for MATLAB.
* Copyright (c) 1984-98 by The MathWorks, Inc.
* All rights reserved.
*============================================================*/
/* $Revision: 1.2 $ */
#include <math.h> /* Needed for the ceil() prototype */
#include "mex.h"
/* If you are using a compiler that equates NaN to be zero, you
* must compile this example using the flag DNAN_EQUALS_ZERO.
* For example:
*
* mex DNAN_EQUALS_ZERO fulltosparse.c
*
* This will correctly define the IsNonZero macro for your C
* compiler. */
#if NAN_EQUALS_ZERO
#define IsNonZero(d) ((d)!=0.0 || mxIsNaN(d))
#else
#define IsNonZero(d) ((d)!=0.0)
#endif
#define PERCENT_SPARSE .20
void mexFunction(
int nlhs, mxArray *plhs[],
Examples of C MEX-Files
3-31
int nrhs, const mxArray *prhs[]
)
{
/* Declare variable. */
int j, k, m, n, nzmax, *irs, *jcs, cmplx, isfull;
double *pr, *pi, *si, *sr;
/* Check for proper number of input and output arguments. */
if (nrhs != 1) {
mexErrMsgTxt("One input argument required.");
}
if(nlhs > 1){
mexErrMsgTxt("Too many output arguments.");
}
/* Check data type of input argument. */
if (!(mxIsDouble(prhs[0]))){
mexErrMsgTxt("Input argument must be of type double.");
}
if (mxGetNumberOfDimensions(prhs[0]) != 2){
mexErrMsgTxt("Input argument must be two dimensional\n");
}
/* Get the size and pointers to input data. */
m = mxGetM(prhs[0]);
n = mxGetN(prhs[0]);
pr = mxGetPr(prhs[0]);
pi = mxGetPi(prhs[0]);
cmplx = (pi==NULL ? 0 : 1);
/* Allocate space for sparse matrix. */
/* NOTE: Assume at most 20% of the data is sparse. Use ceil
* to cause it to round up. */
nzmax = (int)ceil((double)m*(double)n*PERCENT_SPARSE);
/* NOTE: The maximum number of non-zero elements cannot be less
than the number of columns in the matrix. */
if (n>nzmax){
nzmax = n;
}
3 Creating C Language MEX-Files
3-32
plhs[0] = mxCreateSparse(m, n, nzmax, cmplx);
sr = mxGetPr(plhs[0]);
si = mxGetPi(plhs[0]);
irs = mxGetIr(plhs[0]);
jcs = mxGetJc(plhs[0]);
/* Copy non-zeros. */
k = 0;
isfull = 0;
for (j=0; (j<n ); j++) {
int i;
jcs[j] = k;
for (i=0; (i<m ); i++) {
if (IsNonZero(pr[i]) || (cmplx && IsNonZero(pi[i]))) {
/* Check to see if non-zero element will fit in
* allocated output array. If not, set flag and
* print warning. */
if (k>=nzmax){
isfull=1;
mexWarnMsgTxt("Truncating output, more than 20%% of
input is non-zero data.");
break;
}
sr[k] = pr[i];
if (cmplx){
si[k] = pi[i];
}
irs[k] = i;
k++;
}
}
if (isfull)
break;
pr += m;
pi += m;
}
jcs[n] = k;
}
Examples of C MEX-Files
3-33
At the MATLAB prompt, enteri ng
full = eye(5)
full =
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1
creates a ful l , 5-by-5 i denti ty matri x. Usi ng fulltosparse on the ful l matri x
produces the correspondi ng sparse matri x.
spar = fulltosparse(full)
spar =
(1,1) 1
(2,2) 1
(3,3) 1
(4,4) 1
(5,5) 1
Calling MATLAB Functions and Other User-Defined
Functions from Within a MEX-File
I t i s possi bl e to cal l MATLAB functi ons, operators, M-fi l es, and other MEX-fi l es
from wi thi n your C source code by usi ng the API functi on mexCallMATLAB. Thi s
exampl e creates an mxArray, passes vari ous poi nters to a subfuncti on to
acqui re data, and cal l s mexCallMATLAB to cal cul ate the si ne functi on and pl ot
the resul ts.
/* $Revision: 1.1 $ */
/*=============================================================
* sincall.c
*
* Example for illustrating how to use mexCallMATLAB
*
* Creates an mxArray and passes its associated pointers (in
* this demo, only pointer to its real part, pointer to number of
* rows, pointer to number of columns) to subfunction fill() to
* get data filled up, then calls mexCallMATLAB to calculate sin
* function and plot the result.
*
3 Creating C Language MEX-Files
3-34
* This is a MEX-file for MATLAB.
* Copyright (c) 1984-1998 The MathWorks, Inc.
*============================================================*/
#include "mex.h"
#define MAX 1000
/* Subroutine for filling up data */
void fill( double *pr, int *pm, int *pn, int max )
{
int i;
/* You can fill up to max elements, so (*pr)<=max. */
*pm = max/2;
*pn = 1;
for (i=0; i < (*pm); i++)
pr[i]=i*(4*3.14159/max);
}
/* Gateway function */
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[] )
{
int m, n, max=MAX;
mxArray *rhs[1], *lhs[1];
rhs[0] = mxCreateDoubleMatrix(max, 1, mxREAL);
/* Pass the pointers and let fill() fill up data. */
fill(mxGetPr(rhs[0]), &m, &n, MAX);
mxSetM(rhs[0], m);
mxSetN(rhs[0], n);
/* Get the sin wave and plot it. */
mexCallMATLAB(1, lhs, 1, rhs, "sin");
mexCallMATLAB(0, NULL, 1, lhs, "plot");
Examples of C MEX-Files
3-35
/* Clean up allocated memory. */
mxDestroyArray(rhs[0]);
mxDestroyArray(lhs[0]);
return;
}
Runni ng thi s exampl e
sincall
di spl ays the resul ts
3 Creating C Language MEX-Files
3-36
Note: I t i s possi bl e to generate an object of type mxUNKNOWN_CLASS usi ng
mexCallMATLAB. For exampl e, i f you create an M-fi l e that returns two
vari abl es but onl y assi gns one of them a val ue,
function [a,b]=foo[c]
a=2*c;
youl l get thi s warni ng message i n MATLAB:
Warning: One or more output arguments not assigned during call
to 'foo'.
I f you then cal l foo usi ng mexCallMATLAB, the unassi gned output vari abl e wi l l
now be of type mxUNKNOWN_CLASS.
Advanced Topics
3-37
Advanced Topics
These secti ons cover advanced features of MEX-fi l es that you can use when
your appl i cati ons requi re sophi sti cated MEX-fi l es.
Help Files
Because the MATLAB i nterpreter chooses the MEX-fi l e when both an M-fi l e
and a MEX-fi l e wi th the same name are encountered i n the same di rectory, i t
i s possi bl e to use M-fi l es for documenti ng the behavi or of your MEX-fi l es. The
MATLAB help command wi l l automati cal l y fi nd and di spl ay the appropri ate
M-fi l e when hel p i s requested and the i nterpreter wi l l fi nd and execute the
correspondi ng MEX-fi l e when the functi on i s i nvoked.
Linking Multiple Files
I t i s possi bl e to combi ne several object fi l es and to use object fi l e l i brari es when
bui l di ng MEX-fi l es. To do so, si mpl y l i st the addi ti onal fi l es wi th thei r ful l
extensi on, separated by spaces. For exampl e, on the PC
mex circle.c square.obj rectangle.c shapes.lib
i s a l egal command that operates on the .c, .obj, and .lib fi l es to create a
MEX-fi l e cal l ed circle.dll, where dll i s the extensi on correspondi ng to the
MEX-fi l e type on the PC. The name of the resul ti ng MEX-fi l e i s taken from the
fi rst fi l e i n the l i st.
You may fi nd i t useful to use a software devel opment tool l i ke MAKE to manage
MEX-fi l e projects i nvol vi ng mul ti pl e source fi l es. Si mpl y create a MAKEFILE
that contai ns a rul e for produci ng object fi l es from each of your source fi l es and
then i nvoke mex to combi ne your object fi l es i nto a MEX-fi l e. Thi s way you can
ensure that your source fi l es are recompi l ed onl y when necessary.
Variable Scope
Unl i ke M-fi l e functi ons, MEX-fi l e functi ons do not have thei r own vari abl e
workspace. MEX-fi l e functi ons operate i n the cal l ers workspace.
mexEvalString eval uates the stri ng i n the cal l ers workspace. I n addi ti on, you
can use the mexGetArray and mexPutArray routi nes to get and put vari abl es
i nto the cal l ers workspace.
3 Creating C Language MEX-Files
3-38
Memory Management
Memory management wi thi n MEX-fi l es i s not unl i ke memory management for
regul ar C or Fortran appl i cati ons. However, there are speci al consi derati ons
because the MEX-fi l e must exi st wi thi n the context of a l arger appl i cati on, i .e.,
MATLAB i tsel f.
Automatic Cleanup of Temporary Arrays
When a MEX-fi l e returns to MATLAB, i t gi ves to MATLAB the resul ts of i ts
computati ons i n the form of the l eft-hand si de arguments the mxArrays
contai ned wi thi n the plhs[] l i st. Any mxArrays created by the MEX-fi l e that
are not i n thi s l i st are automati cal l y destroyed. I n addi ti on, any memory
al l ocated wi th mxCalloc, mxMalloc, or mxRealloc duri ng the MEX-fi l es
executi on i s automati cal l y freed.
I n general , we recommend that MEX-fi l es destroy thei r own temporary arrays
and free thei r own dynami cal l y al l ocated memory. I t i s more effi ci ent for the
MEX-fi l e to perform thi s cl eanup than to rel y on the automati c mechani sm.
However, there are several ci rcumstances i n whi ch the MEX-fi l e wi l l not reach
i ts normal return statement. The normal return wi l l not be reached i f:
A cal l to mexErrMsgTxt occurs.
A cal l to mexCallMATLAB occurs and the functi on bei ng cal l ed creates an
error. (A MEX-fi l e can trap such errors by usi ng mexSetTrapFlag, but not al l
MEX-fi l es woul d necessari l y need to trap errors.)
The user i nterrupts the MEX-fi l es executi on usi ng Ctrl -C.
The MEX-fi l e runs out of memory. When thi s happens, MATLABs
out-of-memor y handl er wi l l i mmedi atel y ter mi nate the MEX-fi l e.
A careful MEX-fi l e programmer can ensure safe cl eanup of al l temporary
arrays and memory before returni ng i n the fi rst two cases, but not i n the l ast
two cases. I n the l ast two cases, the automati c cl eanup mechani sm i s necessary
to prevent memory l eaks.
Persistent Arrays
You can exempt an array, or a pi ece of memory, from MATLABs automati c
cl eanup by cal l i ng mexMakeArrayPersistent or mexMakeMemoryPersistent.
However, i f a MEX-fi l e creates such persi stent objects, there i s a danger that a
memory l eak coul d occur i f the MEX-fi l e i s cl eared before the persi stent object
i s properl y destroyed. I n order to prevent thi s from happeni ng, a MEX-fi l e that
Advanced Topics
3-39
creates persi stent objects shoul d regi ster a functi on, usi ng mexAtExit, whi ch
wi l l di spose of the objects. (You can use a mexAtExit functi on to di spose of other
resources as wel l ; for exampl e, you can use mexAtExit to cl ose an open fi l e.)
For exampl e, here i s a si mpl e MEX-fi l e that creates a persi stent array and
properl y di sposes of i t.
#include "mex.h"
static int initialized = 0;
static mxArray *persistent_array_ptr = NULL;
void cleanup(void) {
mexPrintf("MEX-file is terminating, destroying array\n");
mxDestroyArray(persistent_array_ptr);
}
void mexFunction(int nlhs,
mxArray *plhs[],
int nrhs,
const mxArray *prhs[])
{
if (!initialized) {
mexPrintf("MEX-file initializing, creating array\n");
/* Create persistent array and register its cleanup. */
persistent_array_ptr = mxCreateDoubleMatrix(1, 1, mxREAL);
mexMakeArrayPersistent(persistent_array_ptr);
mexAtExit(cleanup);
initialized = 1;
/* Set the data of the array to some interesting value. */
*mxGetPr(persistent_array_ptr) = 1.0;
} else {
mexPrintf("MEX-file executing; value of first array
element is %g\n",
*mxGetPr(persistent_array_ptr));
}
}
3 Creating C Language MEX-Files
3-40
Hybrid Arrays
Functi ons such as mxSetPr, mxSetData, and mxSetCell al l ow the di rect
pl acement of memory pi eces i nto an mxArray. mxDestroyArray wi l l destr oy
these pi eces al ong wi th the enti re array. Because of thi s, i t i s possi bl e to create
an array that cannot be destroyed, i .e., an array on whi ch i t i s not safe to cal l
mxDestroyArray. Such an array i s cal l ed a hybrid array, because i t contai ns
both destroyabl e and nondestroyabl e components.
For exampl e, i t i s not l egal to cal l mxFree (or the ANSI free() functi on, for that
matter) on automati c vari abl es. Therefore, i n the fol l owi ng code fragment,
pArray i s a hybri d array.
mxArray *pArray = mxCreateDoubleMatrix(0, 0, mxREAL);
double data[10];
mxSetPr(pArray, data);
mxSetM(pArray, 1);
mxSetN(pArray, 10);
Another exampl e of a hybri d array i s a cel l array or structure, one of whose
chi l dren i s a read-onl y array (an array wi th the const qual i fi er, such as one of
the i nputs to the MEX-fi l e). The array cannot be destroyed because the i nput
to the MEX-fi l e woul d al so be destroyed.
Because hybri d arrays cannot be destroyed, they cannot be cl eaned up by the
automati c mechani sm outl i ned i n Automati c Cl eanup of Temporary Arrays.
As descri bed i n that secti on, the automati c cl eanup mechani sm i s the onl y way
to destroy temporary arrays i n case of a user i nterrupt. Therefore, temporary
hybrid arrays areillegal and may cause your MEX-fi l e to crash.
Al though persi stent hybri d arrays are vi abl e, we recommend avoi di ng thei r
use wherever possi bl e.
How to Debug C Language MEX-Files
3-41
How to Debug C Language MEX-Files
On most pl atforms, i t i s now possi bl e to debug MEX-fi l es whi l e they are
runni ng wi thi n MATLAB. Compl ete source code debuggi ng, i ncl udi ng setti ng
breakpoi nts, exami ni ng vari abl es, and steppi ng through the source code
l i ne-by-l i ne, i s now avai l abl e.
Note: The secti on, Tr oubl eshooti ng, i n Chapter 8 pr ovi des addi ti onal
i nformati on on i sol ati ng probl ems wi th MEX-fi l es.
To debug a MEX-fi l e from wi thi n MATLAB, you must fi rst compi l e the
MEX-fi l e wi th the g opti on to mex.
mex g filename.c
Debugging on UNIX
You wi l l need to start MATLAB from wi thi n a debugger. To do thi s, speci fy the
name of the debugger you want to use wi th the D opti on when starti ng
MATLAB. For exampl e, to use dbx, the UNI X debugger, type
matlab Ddbx
Once the debugger l oads MATLAB i nto memory, you can start i t by i ssui ng a
run command. Now, from wi thi n MATLAB, enabl e MEX-fi l e debuggi ng by
typi ng
dbmex on
at the MATLAB prompt. Then, run the MEX-fi l e that you want to debug as you
woul d ordi nari l y do (ei ther di rectl y or by means of some other functi on or
scri pt). Before executi ng the MEX-fi l e, you wi l l be returned to the debugger.
You may need to tel l the debugger where the MEX-fi l e was l oaded or the name
of the MEX-fi l e, i n whi ch case MATLAB wi l l di spl ay the appropri ate command
for you to use. At thi s poi nt, you are ready to start debuggi ng. You can l i st the
source code for your MEX-fi l e and set breakpoi nts i n i t. I t i s often conveni ent
to set one at mexFunction so that you stop at the begi nni ng of the gateway
functi on. To proceed from the breakpoi nt, i ssue a conti nue command to the
debugger.
3 Creating C Language MEX-Files
3-42
Once you hi t one of your breakpoi nts, you can make ful l use of any faci l i ti es
that your debugger provi des to exami ne vari abl es, di spl ay memory, or i nspect
regi sters. Refer to the documentati on provi ded wi th your debugger for
i nformati on on i ts use.
I f you are at the MATLAB prompt and want to return control to the debugger,
you can i ssue the command
dbmex stop
whi ch al l ows you to gai n access to the debugger so that you can set addi ti onal
breakpoi nts or exami ne source code. To resume executi on, i ssue a conti nue
command to the debugger.
Debugging on Windows
The fol l owi ng secti ons provi de i nstructi ons on how to debug on Mi crosoft
Wi ndows systems usi ng vari ous compi l ers.
Microsoft Compiler. I f you are usi ng the Mi crosoft compi l er:
1 Start the Mi crosoft Devel opment Studi o (Versi on 4.2) or the Mi crosoft
Vi sual Studi o (Versi on 5) by typi ng at the DOS prompt
msdev filename.dll
2 I n the Mi crosoft envi ronment, from the Build menu (Ver si on 4.2) or the
Project menu (Versi on 5.0), sel ect Settings. I n the wi ndow that opens,
sel ect the Debugtab. Thi s opti ons wi ndow contai ns edi t boxes. I n the edi t
box l abel ed Executablefor debugsession, enter the ful l path to where
MATLAB 5 resi des. Al l other edi t boxes shoul d be empty.
3 Open the source fi l es and set a break poi nt on the desi red l i ne of code by
ri ght-cl i cki ng wi th your mouse on the l i ne of code.
4 From the Build menu, sel ect Debug, and cl i ck Go.
5 You wi l l now be abl e to run your MEX-fi l e i n MATLAB and use the Mi crosoft
debuggi ng envi ronment. For more i nformati on on how to debug i n the
Mi crosoft envi ronment, see the Mi crosoft Devel opment Studi o or Mi crosoft
Vi sual Studi o documentati on.
How to Debug C Language MEX-Files
3-43
Watcom Compiler. I f you are usi ng the Watcom compi l er:
1 Start the debugger by typi ng on the DOS command l i ne
WDW
2 The Watcom Debugger starts and a NewProgramwi ndow opens. I n thi s
wi ndow type the ful l path to MATLAB. For exampl e,
c:\matlab\bin\matlab.exe
Then cl i ck OK.
3 From the Break menu, sel ect On ImageLoad and type the name of your
MEX-fi l e DLL i n capi tal l etters. For exampl e,
YPRIME
Then sel ect ADD and cl i ck OK to cl ose the wi ndow.
4 From the Run menu, sel ect GO. Thi s shoul d start MATLAB.
5 When MATLAB starts, i n the command wi ndow change di rectori es to where
your MEX-fi l e resi des and run your MEX-fi l e. I f a message si mi l ar to the
fol l owi ng appears,
LDR: Automatic DLL Relocation in matlab.exe
LDR: DLL filename.dll base <number> relocated due to collision
with matlab.exe
i gnore the message and cl i ck OK.
6 Open the fi l e you want to debug and set breakpoi nts i n the source code.
3 Creating C Language MEX-Files
3-44
4
Creati ng Fortran
MEX-Fi l es
Fortran MEX-Files . . . . . . . . . . . . . . . . . 4-2
MEX-Fi l es and Data Types . . . . . . . . . . . . . . 4-2
The Components of a Fortran MEX-Fi l e . . . . . . . . . 4-2
Examples of Fortran MEX-Files . . . . . . . . . . . 4-9
A Fi rst Exampl e Passi ng a Scal ar . . . . . . . . . . . 4-9
Passi ng Stri ngs . . . . . . . . . . . . . . . . . . . 4-12
Passi ng Arrays of Stri ngs . . . . . . . . . . . . . . . 4-14
Passi ng Matri ces . . . . . . . . . . . . . . . . . . . 4-17
Passi ng Two or More I nputs or Outputs . . . . . . . . . 4-19
Handl i ng Compl ex Data . . . . . . . . . . . . . . . . 4-22
Dynami c Al l ocati on of Memory . . . . . . . . . . . . . 4-26
Handl i ng Sparse Matri ces . . . . . . . . . . . . . . . 4-28
Cal l i ng MATLAB Functi ons from Fortran MEX-Fi l es . . . . 4-32
Advanced Topics . . . . . . . . . . . . . . . . . . 4-36
Hel p Fi l es . . . . . . . . . . . . . . . . . . . . . 4-36
Li nki ng Mul ti pl e Fi l es . . . . . . . . . . . . . . . . 4-36
Vari abl e Scope . . . . . . . . . . . . . . . . . . . . 4-36
Memory Management . . . . . . . . . . . . . . . . . 4-37
Howto DebugFortran LanguageMEX-Files . . . . . 4-38
Debuggi ng on UNI X . . . . . . . . . . . . . . . . . 4-38
Debuggi ng on Wi ndows . . . . . . . . . . . . . . . . 4-39
4 Creating Fortran MEX-Files
4-2
Fortran MEX-Files
Fortran MEX-fi l es are bui l t by usi ng the mex scri pt to compi l e your Fortran
source code wi th addi ti onal cal l s to API routi nes.
Directory Organization
Thi s tabl e l i sts the l ocati on of the fi l es on your di sk that are associ ated wi th the
creati on of For tr an l anguage MEX-fi l es.
Appendi x B, Di rectory Organi zati on, descri bes the API -rel ated di rectori es
and fi l es.
MEX-Files and Data Types
MEX-fi l es i n Fortran can onl y create doubl e-preci si on data and stri ngs (unl i ke
thei r C counterparts, whi ch can create any data type supported by MATLAB).
You can treat Fortran MEX-fi l es, once compi l ed, exactl y l i ke M-functi ons.
The Components of a Fortran MEX-File
Thi s secti on di scusses the speci fi c el ements needed i n a Fortran MEX-fi l e. The
source code for a Fortran MEX-fi l e, l i ke the C MEX-fi l e, consi sts of two di sti nct
parts:
A computational routinethat contai ns the code for performi ng the
computati ons that you want i mpl emented i n the MEX-fi l e. Computati ons
can be numeri cal computati ons as wel l as i nputti ng and outputti ng data.
A gatewayroutinethat i nterfaces the computati onal routi ne wi th MATLAB
by the entry poi nt mexFunction and i ts parameters prhs, nrhs, plhs, nlhs,
where prhs i s an array of ri ght-hand i nput arguments, nrhs i s the number
of ri ght-hand i nput arguments, plhs i s an array of l eft-hand output
Platform Directory
Wi ndows <matlab>\extern
UNI X <matlab>/extern
where:
<matlab> i s the MATLAB root di rectory
Fortran MEX-Files
4-3
arguments, and nlhs i s the number of l eft-hand output arguments. The
gateway cal l s the computati onal routi ne as a subrouti ne.
The computati onal and gateway routi nes may be separate or combi ned. Fi gure
4-1 shows how i nputs enter an API functi on, what functi ons the gateway
functi on performs, and how output returns to MATLAB.
4 Creating Fortran MEX-Files
4-4
Figure 4-1: Fortran MEX Cycle
integer A
A = prhs(1)
MATLAB
A cal l to
MEX-fi l e func:
[C,D]=func(A,B)
tel l s MATLAB to
pass vari abl es A and B
to your MEX-fi l e. C
and D are l eft
unassi gned.
integer C
C = plhs(1)
integer B
B = prhs(2)
integer D
D = plhs(2)
INPUTS
OUTPUTS
func.f
subroutine mexFunction(
nlhs, plhs, nrhs, prhs)
integer plhs(*), prhs(*), nlhs, nrhs
I n the gateway routi ne:
Use the mxCreate functi ons to create the
MATLAB arrays for your output
arguments. Set plhs(1), (2), to the
poi nters to the newl y created MATLAB
arrays.
Use the mxGet functi ons to extract your
data from prhs(1), (2),
Cal l your Fortran subrouti ne passi ng
the i nput and output data poi nters as
functi on parameters usi ng %val.
MATLAB
On return from
MEX-fi l e func:
[C,D]=func(A,B)
plhs(1) i s assi gned to
C and plhs(2) i s
assi gned to D.
Fortran MEX-Files
4-5
The Pointer Concept
The MATLAB API works wi th a uni que data type, the mxArray. Because there
i s no way to create a new data type i n Fortran, MATLAB passes a speci al
i denti fi er, cal l ed a poi nter, to a Fortran program. You can get i nformati on
about an mxArray by passi ng thi s poi nter to vari ous API functi ons cal l ed
Access Routi nes. These access routi nes al l ow you to get a nati ve Fortran data
type contai ni ng exactl y the i nformati on you want, i .e., the si ze of the mxArray,
whether or not i t i s a stri ng, or i ts data contents.
There are several i mpl i cati ons when usi ng poi nters i n Fortran:
The %val construct.
I f your Fortran compi l er supports the %val construct, then there i s one type
of poi nter you can use wi thout requi ri ng an access routi ne, namel y a poi nter
to data (i .e., the poi nter r etur ned by mxGetPr or mxGetPi). You can use %val
to pass thi s poi nters contents to a subrouti ne, where i t i s decl ared as a
For tr an doubl e-pr eci si on matr i x.
I f your Fortran compi l er does not support the %val construct, you must use
the mxCopy__ routi nes (e.g., mxCopyPtrToReal8) to access the contents of the
poi nter. For more i nformati on about the %val construct and an exampl e, see
the secti on, The %val Construct, i n thi s chapter.
Vari abl e decl arati ons.
To use poi nters properl y, you must decl are them to be the correct si ze. On
DEC Al pha and 64-bi t SGI machi nes, al l poi nters shoul d be decl ared as
integer*8. On al l other pl atforms, poi nters shoul d be decl ared as integer*4.
I f your Fortran compi l er supports preprocessi ng wi th the C preprocessor, you
can use the preprocessi ng stage to map poi nters to the appropri ate
decl arati on. I n UNI X, see the exampl es endi ng wi th .F i n the examples
di rectory for a possi bl e approach.
Caution: Decl ari ng a poi nter to be the i ncorrect si ze can cause your program
to crash.
4 Creating Fortran MEX-Files
4-6
The Gateway Routine
The entry poi nt to the gateway subrouti ne must be named mexFunction and
must contai n these parameters:
subroutine mexFunction(nlhs, plhs, nrhs, prhs)
integer plhs(*), prhs(*)
integer nlhs, nrhs
Note: Fortran i s case i nsensi ti ve. Thi s document uses mi xed case functi on
names for ease of readi ng.
I n a Fortran MEX-fi l e, the parameters nlhs and nrhs contai n the number of
l eft- and ri ght-hand arguments wi th whi ch the MEX-fi l e i s i nvoked. prhs i s a
l ength nrhs array that contai ns poi nters to the ri ght-hand si de i nputs to the
MEX-fi l e, and plhs i s a l ength nlhs array that contai ns poi nters to the
l eft-hand si de outputs that your Fortran functi on generates.
I n the syntax of the MATLAB l anguage, functi ons have the general form
[a,b,c,] = fun(d,e,f,)
where the el l i psi s ()denotes addi ti onal terms of the same format. The a,b,c,
are l eft-hand arguments and the d,e,f, are ri ght-hand arguments.
As an exampl e of the gateway routi ne, consi der i nvoki ng a MEX-fi l e from the
MATLAB workspace wi th the command
x = fun(y,z);
the MATLAB i nterpreter cal l s mexFunction wi th the arguments
nlhs = 1
nrhs = 2
plhs
prhs
Z
Fortran MEX-Files
4-7
plhs i s a 1-el ement C array where the si ngl e el ement i s a null poi nter. prhs i s
a 2-el ement C array where the fi rst el ement i s a poi nter to an mxArray named
Y and the second el ement i s a poi nter to an mxArray named Z.
The parameter plhs poi nts at nothi ng because the output x i s not created unti l
the subrouti ne executes. I t i s the responsi bi l i ty of the gateway routi ne to create
an output array and to set a poi nter to that array i n plhs(1). I f plhs(1) i s l eft
unassi gned, MATLAB pri nts a warni ng message stati ng that no output has
been assi gned.
Note: I t i s possi bl e to return an output val ue even i f nlhs = 0. Thi s
corresponds to returni ng the resul t i n the ans vari abl e.
The gateway routi ne shoul d val i date the i nput arguments and cal l
mexErrMsgTxt i f anythi ng i s ami ss. Thi s step i ncl udes checki ng the number,
type, and si ze of the i nput arrays as wel l as exami ni ng the number of output
arrays. The exampl es i ncl uded l ater i n thi s secti on i l l ustrate thi s techni que.
The mx functi ons provi de a set of access methods (subrouti nes) for
mani pul ati ng MATLAB arrays. These functi ons are ful l y documented i n the
onl i ne API reference pages. The mx prefi x i s shorthand for mxArray and i t
means that the functi on enabl es you to access and/or mani pul ate some of the
i nformati on i n the MATLAB array. For exampl e, mxGetPr gets the real data
from the MATLAB array. Addi ti onal routi nes are provi ded for transferri ng
data between MATLAB arrays and Fortran arrays.
The gateway routi ne must cal l mxCreateFull, mxCreateSparse, or
mxCreateString to create MATLAB arrays of the requi red si zes i n whi ch to
return the resul ts. The return val ues from these cal l s shoul d be assi gned to the
appropri ate el ements of plhs.
The gateway routi ne may cal l mxCalloc to al l ocate temporary work arrays for
the computati onal routi ne i f i t needs them.
The gateway routi ne shoul d cal l the computati onal routi ne to perform the
desi red cal cul ati ons or operati ons. There are a number of addi ti onal routi nes
that MEX-fi l es can use. These routi nes are di sti ngui shed by the i ni ti al
characters mex, as i n mexCallMATLAB and mexErrMsgTxt.
4 Creating Fortran MEX-Files
4-8
When a MEX-fi l e compl etes i ts task, i t returns control to MATLAB. Any
MATLAB arrays that are created by the MEX-fi l e that are not returned to
MATLAB through the l eft-hand si de arguments are automati cal l y destroyed.
The %val Construct
The %val construct i s supported by most, but not al l , Fortran compi l ers.
DI GI TAL Vi sual Fortran does support the construct. %val causes the val ue of
the vari abl e, rather than the address of the vari abl e, to be passed to the
subrouti ne. I f you are usi ng a Fortran compi l er that does not support the %val
construct, you must copy the array val ues i nto a temporary true Fortran array
usi ng speci al routi nes. For exampl e, consi der a gateway routi ne that cal l s i ts
computati onal routi ne, yprime, by
call yprime(%val(yp), %val(t), %val(y))
I f your Fortran compi l er does not support the %val construct, you woul d repl ace
the cal l to the computati onal subrouti ne wi th
C Copy array pointers to local arrays.
call mxCopyPtrToReal8(t, tr, 1)
call mxCopyPtrToReal8(y, yr, 4)
C
C Call the computational subroutine.
call yprime(ypr, tr, yr)
C
C Copy local array to output array pointer.
call mxCopyReal8ToPtr(ypr, yp, 4)
You must al so add the fol l owi ng decl arati on l i ne to the top of the gateway
routi ne.
real*8 ypr(4), tr, yr(4)
Note that i f you use mxCopyPtrToReal8 or any of the other mxCopy__ routi nes,
the si ze of the arrays decl ared i n the Fortran gateway routi ne must be greater
than or equal to the si ze of the i nputs to the MEX-fi l e comi ng i n from MATLAB.
Otherwi se mxCopyPtrToReal8 wi l l not work correctl y.
Examples of Fortran MEX-Files
4-9
Examples of Fortran MEX-Files
The next secti ons of thi s chapter i ncl ude exampl es of di fferent MEX-fi l es. The
MATLAB 5 API provi des a set of routi nes for Fortran that handl e
doubl e-preci si on data and stri ngs i n MATLAB. For each data type, there i s a
speci fi c set of functi ons that you can use for data mani pul ati on.
Noteto UNIX Users: The exampl e Fortran fi l es i n the di rectory
<matlab>/extern/examples/refbook have extensi ons .F and .f. The
di sti ncti on between these extensi ons i s that the .F fi l es need to be
preprocessed.
Note: You can fi nd the most recent versi ons of the exampl e programs from
thi s chapter at the anonymous FTP server,
ftp.mathworks.com/pub/tech-support/library/matlab5/extern/examples/refbook
A First Example Passing a Scalar
Lets l ook at a si mpl e exampl e of Fortran code and i ts MEX-fi l e equi val ent.
Here i s a Fortran computati onal routi ne that takes a scal ar and doubl es i t.
subroutine timestwo(y, x)
real*8 x, y
C
y = 2.0 * x
return
end
Bel ow i s the same functi on wri tten i n the MEX-fi l e format.
C--------------------------------------------------------------
C timestwo.f
C
C Multiply the input argument by 2.
4 Creating Fortran MEX-Files
4-10
C This is a MEX-file for MATLAB.
C Copyright (c) 1984-1998 The MathWorks, Inc.
C $Revision: 1.6 $
subroutine mexFunction(nlhs, plhs, nrhs, prhs)
C--------------------------------------------------------------
C (integer) Replace integer by integer*8 on the DEC Alpha
C and the SGI 64-bit platforms.
C
integer plhs(*), prhs(*)
integer mxGetPr, mxCreateFull
integer x_pr, y_pr
C--------------------------------------------------------------
C
integer nlhs, nrhs
integer mxGetM, mxGetN, mxIsNumeric
integer m, n, size
real*8 x, y
C Check for proper number of arguments.
if(nrhs .ne. 1) then
call mexErrMsgTxt('One input required.')
elseif(nlhs .ne. 1) then
call mexErrMsgTxt('One output required.')
endif
C Get the size of the input array.
m = mxGetM(prhs(1))
n = mxGetN(prhs(1))
size = m*n
C Check to ensure the input is a number.
if(mxIsNumeric(prhs(1)) .eq. 0) then
call mexErrMsgTxt('Input must be a number.')
endif
Examples of Fortran MEX-Files
4-11
C Create matrix for the return argument.
plhs(1) = mxCreateFull(m, n, 0)
x_pr = mxGetPr(prhs(1))
y_pr = mxGetPr(plhs(1))
call mxCopyPtrToReal8(x_pr, x, size)
C Call the computational subroutine.
call timestwo(y, x)
C Load the data into y_pr, which is the output to MATLAB.
call mxCopyReal8ToPtr(y, y_pr, size)
return
end
subroutine timestwo(y, x)
real*8 x, y
C
y = 2.0 * x
return
end
To compi l e and l i nk thi s exampl e source fi l e, at the MATLAB prompt type
mex timestwo.f
Thi s carri es out the necessary steps to create the MEX-fi l e cal l ed timestwo
wi th an extensi on correspondi ng to the machi ne type on whi ch youre runni ng.
You can now cal l timestwo as i f i t were an M-functi on.
x = 2;
y = timestwo(x)
y =
4
4 Creating Fortran MEX-Files
4-12
Passing Strings
Passi ng stri ngs from MATLAB to a Fortran MEX-fi l e i s strai ghtforward. Thi s
program accepts a stri ng and returns the characters i n reverse order.
C $Revision: 1.9 $
C==============================================================
C
C revord.f
C Example for illustrating how to copy string data from
C MATLAB to a Fortran-style string and back again.
C
C Takes a string and returns a string in reverse order.
C
C This is a MEX-file for MATLAB.
C Copyright (c) 1984-1998 The MathWorks, Inc.
C==============================================================
subroutine revord(input_buf, strlen, output_buf)
character input_buf(*), output_buf(*)
integer i, strlen
do 10 i=1,strlen
output_buf(i) = input_buf(strleni+1)
10 continue
return
end
Bel ow i s the gateway functi on that cal l s the computati onal routi ne.
C The gateway routine
subroutine mexFunction(nlhs, plhs, nrhs, prhs)
integer nlhs, nrhs
C--------------------------------------------------------------
C (integer) Replace integer by integer*8 on the DEC Alpha
C and the SGI 64-bit platforms.
C
integer plhs(*), prhs(*)
integer mxCreateString, mxGetString
C--------------------------------------------------------------
C
Examples of Fortran MEX-Files
4-13
integer mxGetM, mxGetN, mxIsString
integer status, strlen
character*100 input_buf, output_buf
C Check for proper number of arguments.
if (nrhs .ne. 1) then
call mexErrMsgTxt('One input required.')
elseif (nlhs .gt. 1) then
call mexErrMsgTxt('Too many output arguments.')
C The input must be a string.
elseif(mxIsString(prhs(1)) .ne. 1) then
call mexErrMsgTxt('Input must be a string.')
C The input must be a row vector.
elseif (mxGetM(prhs(1)) .ne. 1) then
call mexErrMsgTxt('Input must be a row vector.')
endif
C Get the length of the input string.
strlen = mxGetM(prhs(1))*mxGetN(prhs(1))
C Get the string contents (dereference the input integer).
status = mxGetString(prhs(1), input_buf, 100)
C Check if mxGetString is successful.
if (status .ne. 0) then
call mexErrMsgTxt('String length must be less than 100.')
endif
C Initialize outbuf_buf to blanks. This is necessary on some
C compilers.
output_buf = ' '
C Call the computational subroutine.
call revord(input_buf, strlen, output_buf)
4 Creating Fortran MEX-Files
4-14
C Set output_buf to MATLAB mexFunction output.
plhs(1) = mxCreateString(output_buf)
return
end
After checki ng for the correct number of i nputs, thi s MEX-fi l e gateway functi on
veri fi es that the i nput was ei ther a row or col umn vector stri ng. I t then fi nds
the si ze of the stri ng and pl aces the stri ng i nto a Fortran character array. Note
that i n the case of character stri ngs, i t i s not necessary to copy the data i nto a
Fortran character array by usi ng mxCopyPtrToCharacter. I n fact,
mxCopyPtrToCharacter works onl y wi th MAT-fi l es. (For more i nformati on
about MAT-fi l es, see Chapter 5, Data Export and I mport.)
For an i nput stri ng
x = 'hello world';
typi ng
y = revord(x)
produces
y =
dlrow olleh
Passing Arrays of Strings
Passi ng arrays of stri ngs i nvol ves a sl i ght compl i cati on from the previ ous
exampl e i n the Passi ng Stri ngs secti on of thi s chapter. Because MATLAB
stores el ements of a matri x by col umn i nstead of by row, i t i s essenti al that the
si ze of the stri ng array be correctl y defi ned i n the Fortran MEX-fi l e. The key
poi nt i s that the row and col umn si zes as defi ned i n MATLAB must be reversed
i n the Fortran MEX-fi l e; consequentl y, when returni ng to MATLAB, the
output matri x must be transposed.
Thi s exampl e pl aces a stri ng array/character matri x i nto MATLAB as output
arguments rather than pl aci ng i t di rectl y i nto the workspace. I nsi de MATLAB,
cal l thi s functi on by typi ng
passstr;
Examples of Fortran MEX-Files
4-15
You wi l l get the matri x mystring of si ze 5-by-15. There are some mani pul ati ons
that need to be done here. The ori gi nal stri ng matri x i s of the si ze 5-by-15.
Because of the way MATLAB reads and ori ents el ements i n matri ces, the si ze
of the matr i x must be defi ned as M=15 and N=5 from the MEX-fi l e. After the
matri x i s put i nto MATLAB, the matri x must be transposed.
C $Revision: 1.6 $
C==============================================================
C
C passstr.f
C Example for illustrating how to pass a character matrix
C from Fortran to MATLAB.
C
C Passes a string array/character matrix into MATLAB as
C output arguments rather than placing it directly into the
C workspace.
C
C This is a MEX-file for MATLAB.
C Copyright (c) 1984-1998 The MathWorks, Inc.
C==============================================================
subroutine mexFunction(nlhs, plhs, nrhs, prhs)
C--------------------------------------------------------------
C (integer) Replace integer by integer*8 on the DEC Alpha
C and the SGI 64-bit platforms.
C
integer plhs(*), prhs(*)
integer p_str, mxCreateString
C--------------------------------------------------------------
C
integer nlhs, nrhs
integer i
character*75 thestring
character*15 string(5)
4 Creating Fortran MEX-Files
4-16
C Create the string to passed into MATLAB.
string(1) = 'MATLAB '
string(2) = 'The Scientific '
string(3) = 'Computing '
string(4) = 'Environment '
string(5) = ' by TMW, Inc.'
C Concatenate the set of 5 strings into a long string.
thestring = string(1)
do 10 i = 2, 6
thestring = thestring(:((i1)*15)) // string(i)
10 continue
C Create the string matrix to be passed into MATLAB.
C Set the matrix size to be M=15 and N=5.
p_str = mxcreatestring(thestring)
call mxSetM(p_str, 15)
call mxSetN(p_str, 5)
C Transpose the resulting matrix in MATLAB.
call mexCallMATLAB(1, plhs, 1, p_str, 'transpose')
return
end
Typi ng
passstr
at the MATLAB prompt produces thi s resul t
ans =
MATLAB
The Scientific
Computing
Environment
by TMW, Inc.
Examples of Fortran MEX-Files
4-17
Passing Matrices
I n MATLAB, you can pass matri ces i nto and out of MEX-fi l es wri tten i n
Fortran. You can mani pul ate the MATLAB arrays by usi ng mxGetPr and
mxGetPi to assi gn poi nters to the real and i magi nary parts of the data stored
i n the MATLAB arrays, and you can create new MATLAB arrays from wi thi n
your MEX-fi l e by usi ng mxCreateFull.
Thi s exampl e takes a real 2-by-3 matri x and squares each el ement.
C--------------------------------------------------------------
C
C matsq.f
C
C Squares the input matrix
C This is a MEX-file for MATLAB.
C Copyright (c) 1984-1998 The MathWorks, Inc.
C $Revision: 1.7 $
C--------------------------------------------------------------
subroutine matsq(y, x, m, n)
real*8 x(m,n), y(m,n)
integer m, n
C
do 20 i=1,m
do 10 j=1,n
y(i,j)= x(i,j)**2
10 continue
20 continue
return
end
4 Creating Fortran MEX-Files
4-18
Thi s i s the gateway routi ne that cal l s the computati onal subrouti ne.
subroutine mexFunction(nlhs, plhs, nrhs, prhs)
C--------------------------------------------------------------
C (integer) Replace integer by integer*8 on the DEC Alpha
C and the SGI 64-bit platforms.
C
integer plhs(*), prhs(*)
integer mxCreateFull, mxGetPr
integer x_pr, y_pr
C--------------------------------------------------------------
C
integer nlhs, nrhs
integer mxGetM, mxGetN, mxIsNumeric
integer m, n, size
real*8 x(1000), y(1000)
C Check for proper number of arguments.
if(nrhs .ne. 1) then
call mexErrMsgTxt('One input required.')
elseif(nlhs .ne. 1) then
call mexErrMsgTxt('One output required.')
endif
C Get the size of the input array.
m = mxGetM(prhs(1))
n = mxGetN(prhs(1))
size = m*n
C Column * row should be smaller than 1000.
if(size.gt.1000) then
call mexErrMsgTxt('Row * column must be <= 1000.')
endif
C Check to ensure the array is numeric (not strings).
if(mxIsNumeric(prhs(1)) .eq. 0) then
call mexErrMsgTxt('Input must be a numeric array.')
endif
Examples of Fortran MEX-Files
4-19
C Create matrix for the return argument.
plhs(1) = mxCreateFull(m, n, 0)
x_pr = mxGetPr(prhs(1))
y_pr = mxGetPr(plhs(1))
call mxCopyPtrToReal8(x_pr, x, size)
C Call the computational subroutine.
call matsq(y, x, m, n)
C Load the data into y_pr, which is the output to MATLAB.
call mxCopyReal8ToPtr(y, y_pr, size)
return
end
After performi ng error checki ng to ensure that the correct number of i nputs
and outputs was assi gned to the gateway subrouti ne and to veri fy the i nput
was i n fact a numeri c matri x, matsq.f creates a matri x for the argument
returned from the computati onal subrouti ne. The i nput matri x data i s then
copi ed to a Fortran matri x by usi ng mxCopyPtrToReal8. Now the computati onal
subrouti ne can be cal l ed, and the return argument can then be pl aced i nto
y_pr, the poi nter to the output, usi ng mxCopyReal8ToPtr.
For a 2-by-3 real matri x,
x = [1 2 3; 4 5 6];
typi ng
y = matsq(x)
produces thi s resul t
y =
1 4 9
16 25 36
Passing Two or More Inputs or Outputs
The plhs and prhs parameters are vectors that contai n poi nters to each
l eft-hand si de (output) vari abl e and ri ght-hand si de (i nput) vari abl e.
Accordi ngl y, plhs(1) contai ns a poi nter to the fi rst l eft-hand si de argument,
plhs(2) contai ns a poi nter to the second l eft-hand si de argument, and so on.
4 Creating Fortran MEX-Files
4-20
Li kewi se, prhs(1) contai ns a poi nter to the fi rst ri ght-hand si de argument,
prhs(2) poi nts to the second, and so on.
For exampl e, heres a routi ne that mul ti pl i es an i nput scal ar ti mes an i nput
scal ar or matr i x. Thi s i s the For tr an code for the computati onal subr outi ne.
subroutine xtimesy(x, y, z, m, n)
real*8 x, y(3,3), z(3,3)
integer m, n
do 20 i=1,m
do 10 j=1,n
z(i,j)=x*y(i,j)
10 continue
20 continue
return
end
Bel ow i s the gateway routi ne that cal l s xtimesy, the computati on subrouti ne
that mul ti pl i es a scal ar by a scal ar or matri x.
C--------------------------------------------------------------
C
C xtimesy.f
C
C Multiply the first input by the second input.
C This is a MEX file for MATLAB.
C Copyright (c) 1984-1998 The MathWorks, Inc.
C $Revision: 1.6 $
subroutine mexFunction(nlhs, plhs, nrhs, prhs)
C--------------------------------------------------------------
C (integer) Replace integer by integer*8 on the DEC Alpha
C and the SGI 64-bit platforms.
C
integer plhs(*), prhs(*)
integer mxCreateFull
integer x_pr, y_pr, z_pr
C--------------------------------------------------------------
C
Examples of Fortran MEX-Files
4-21
integer nlhs, nrhs
integer m, n, size
integer mxGetM, mxGetN, mxIsNumeric
real*8 x, y(3,3), z(3,3)
C Check for proper number of arguments.
if (nrhs .ne. 2) then
call mexErrMsgTxt('Two inputs required.')
elseif (nlhs .ne. 1) then
call mexErrMsgTxt('One output required.')
endif
C Check to see both inputs are numeric.
if (mxIsNumeric(prhs(1)) .ne. 1) then
call mexErrMsgTxt('Input # 1 is not a numeric.')
elseif (mxIsNumeric(prhs(2)) .ne. 1) then
call mexErrMsgTxt('Input #2 is not a numeric array.')
endif
C Check that input #1 is a scalar.
m = mxGetM(prhs(1))
n = mxGetN(prhs(1))
if(n .ne. 1 .or. m .ne. 1) then
call mexErrMsgTxt('Input #1 is not a scalar.')
endif
C Get the size of the input matrix.
m = mxGetM(prhs(2))
n = mxGetN(prhs(2))
size = m*n
C Create matrix for the return argument.
plhs(1) = mxCreateFull(m, n, 0)
x_pr = mxGetPr(prhs(1))
y_pr = mxGetPr(prhs(2))
z_pr = mxGetPr(plhs(1))
4 Creating Fortran MEX-Files
4-22
C Load the data into Fortran arrays.
call mxCopyPtrToReal8(x_pr, x, 1)
call mxCopyPtrToReal8(y_pr, y, size)
C Call the computational subroutine.
call xtimesy(x, y, z, m, n)
C Load the output into a MATLAB array.
call mxCopyReal8ToPtr(z, z_pr, size)
return
end
As thi s exampl e shows, creati ng MEX-fi l e gateways that handl e mul ti pl e
i nputs and outputs i s strai ghtforward. Al l you need to do i s keep track of whi ch
i ndi ces of the vectors prhs and plhs correspond to whi ch i nput and output
arguments of your functi on. I n thi s exampl e, the i nput vari abl e x corresponds
to prhs(1) and the i nput vari abl e y to prhs(2).
For an i nput scal ar x and a real 3-by-3 matri x,
x = 3; y = ones(3);
typi ng
z = xtimesy(x, y)
yi el ds thi s resul t
z =
3 3 3
3 3 3
3 3 3
Handling Complex Data
MATLAB stores compl ex doubl e-preci si on data as two vectors of numbers
one contai ns the real data and one contai ns the i magi nary data. The API
provi des two functi ons, mxCopyPtrToComplex16 and mxCopyComplex16ToPtr,
whi ch al l ow you to copy the MATLAB data to a nati ve complex*16 Fortran
array.
Examples of Fortran MEX-Files
4-23
Thi s exampl e takes two compl ex vector s (of l ength 3) and convol ves them.
C $Revision: 1.9 $
C==============================================================
C
C convec.f
C Example for illustrating how to pass complex data from
C MATLAB to FORTRAN (using COMPLEX data type) and back
C again.
C
C Convolves two complex input vectors.
C
C This is a MEX-file for MATLAB.
C Copyright (c) 1984-1998 The MathWorks, Inc.
C==============================================================
C
C Computational subroutine
subroutine convec(x, y, z, nx, ny)
complex*16 x(*), y(*), z(*)
integer nx, ny
C Initialize the output array.
do 10 i=1,nx+ny1
z(i) = (0.0,0.0)
10 continue
do 30 i=1,nx
do 20 j=1,ny
z(i+j1) = z(i+j1) + x(i) * y(j)
20 continue
30 continue
return
end
4 Creating Fortran MEX-Files
4-24
C The gateway routine.
subroutine mexFunction(nlhs, plhs, nrhs, prhs)
integer nlhs, nrhs
C--------------------------------------------------------------
C (integer) Replace integer by integer*8 on the DEC Alpha
C and the SGI 64-bit platforms
C
integer plhs(*), prhs(*)
integer mxGetPr, mxGetPi, mxCreateFull
C--------------------------------------------------------------
C
integer mx, nx, my, ny, nz
integer mxGetM, mxGetN, mxIsComplex
complex*16 x(100), y(100), z(199)
C Check for proper number of arguments.
if (nrhs .ne. 2) then
call mexErrMsgTxt('Two inputs required.')
elseif (nlhs .gt. 1) then
call mexErrMsgTxt('Too many output arguments.')
endif
C Check that inputs are both row vectors.
mx = mxGetM(prhs(1))
nx = mxGetN(prhs(1))
my = mxGetM(prhs(2))
ny = mxGetN(prhs(2))
nz = nx+ny1
C Only handle row vector input.
if(mx .ne. 1 .or. my .ne. 1) then
call mexErrMsgTxt('Both inputs must be row vector.')
C Check sizes of the two input.
elseif(nx .gt. 100 .or. ny .gt. 100) then
call mexErrMsgTxt('Inputs must have less than 100
elements.')
Examples of Fortran MEX-Files
4-25
C Check to see both inputs are complex.
elseif ((mxIsComplex(prhs(1)) .ne. 1) .or. +
(mxIsComplex(prhs(2)) .ne. 1)) then
call mexErrMsgTxt('Inputs must be complex.')
endif
C Create the output array.
plhs(1) = mxCreateFull(1, nz, 1)
C Load the data into Fortran arrays(native COMPLEX data).
call mxCopyPtrToComplex16(mxGetPr(prhs(1)),
mxGetPi(prhs(1)), x, nx)
call mxCopyPtrToComplex16(mxGetPr(prhs(2)),
mxGetPi(prhs(2)), y, ny)
C Call the computational subroutine.
call convec(x, y, z, nx, ny)
C Load the output into a MATLAB array.
call mxCopyComplex16ToPtr(z,mxGetPr(plhs(1)),
mxGetPi(plhs(1)), nz)
return
end
Enteri ng these numbers at the MATLAB prompt
x = [3 1i, 4 + 2i, 7 3i]
x =
3.0000 1.0000i 4.0000 + 2.0000i 7.0000 3.0000i
y = [8 6i, 12 + 16i, 40 42i]
y =
8.0000 6.0000i 12.0000 +16.0000i 40.0000 42.0000i
and i nvoki ng the new MEX-fi l e
z = convec(x, y)
4 Creating Fortran MEX-Files
4-26
resul ts i n
z =
1.0e+02 *
Columns 1 through 4
0.1800 0.2600i 0.9600 + 0.2800i 1.3200 1.4400i
3.7600 0.1200i
Column 5
1.5400 4.1400i
whi ch agrees wi th the resul ts the bui l t-i n MATLAB functi on conv.m produces.
Dynamic Allocation of Memory
I t i s possi bl e to al l ocate memory dynami cal l y i n a Fortran MEX-fi l e, but you
must use %val to do i t. Thi s exampl e takes an i nput matri x of real data and
doubl es each of i ts el ements.
C $Revision: 1.5 $
C==============================================================
C
C dblmat.f
C Example for illustrating how to use %val.
C Doubles the input matrix. The demo only handles real part C
of input.
C NOTE: If your Fortran compiler does not support %val,
C use mxCopy_routine.
C
C This is a MEX-file for MATLAB.
C Copyright (c) 1984-1998 The MathWorks, Inc.
C==============================================================
C
Examples of Fortran MEX-Files
4-27
C Computational subroutine
subroutine dbl_mat(out_mat, in_mat, size)
integer size, i
real*8 out_mat(*), in_mat(*)
do 10 i=1,size
out_mat(i) = 2*in_mat(i)
10 continue
return
end
C Gateway subroutine
subroutine mexfunction(nlhs, plhs, nrhs, prhs)
C--------------------------------------------------------------
C (integer) Replace integer by integer*8 on the DEC Alpha
C and the SGI 64-bit platforms.
C
integer plhs(*), prhs(*)
integer pr_in, pr_out
integer mxGetPr, mxCreateFull
C--------------------------------------------------------------
C
integer nlhs, nrhs, mxGetM, mxGetN
integer m_in, n_in, size
if(nrhs .ne. 1) then
call mexErrMsgTxt('One input required.')
endif
if(nlhs .gt. 1) then
call mexErrMsgTxt('Less than one output required.')
endif
4 Creating Fortran MEX-Files
4-28
m_in = mxGetM(prhs(1))
n_in = mxGetN(prhs(1))
size = m_in * n_in
pr_in = mxGetPr(prhs(1))
plhs(1) = mxCreateFull(m_in, n_in, 0)
pr_out = mxGetPr(plhs(1))
C Call the computational routine.
call dbl_mat(%val(pr_out), %val(pr_in), size)
return
end
For an i nput 2-by-3 matri x
x = [1 2 3; 4 5 6];
typi ng
y = dblmat(x)
yi el ds
y =
2 4 6
8 10 12
Handling Sparse Matrices
The MATLAB 5 API provi des a set of functi ons that al l ow you to create and
mani pul ate sparse matri ces from wi thi n your MEX-fi l es. There are speci al
parameters associ ated wi th sparse matri ces, namel y ir, jc, and nzmax. For
i nformati on on how to use these parameters and how MATLAB stores sparse
matri ces i n general , refer to The MATLAB Array secti on i n Chapter 1 of thi s
book.
Note: Sparse array i ndexi ng i s zero based, not one based.
Examples of Fortran MEX-Files
4-29
Thi s exampl e i l l ustrates how to popul ate a sparse matri x.
C $Revision: 1.1 $
C==============================================================
C
C fulltosparse.f
C Example for illustrating how to populate a sparse matrix.
C For the purpose of this example, you must pass in a
C non-sparse 2-dimensional argument of type real double.
C
C This is a MEX-file for MATLAB.
C Copyright (c) 1984-98 by The MathWorks, Inc.
C==============================================================
C Load sparse data subroutine.
function loadsparse(a, b, ir, jc, m, n, nzmax)
integer nzmax, m, n
integer ir(*), jc(*)
real*8 a(*), b(*)
integer i, j, k
C Copy nonzeros.
k = 1
do 100 j=1,n
C NOTE: Sparse indexing is zero based.
jc(j) = k1
do 200 i=1,m
if (a((j1)*m+i).ne. 0.0) then
if (k .gt. nzmax) then
jc(n+1) = nzmax
loadsparse = 1
goto 300
endif
b(k) = a((j1)*m+i)
C NOTE: Sparse indexing is zero based.
ir(k) = i1
k = k+1
endif
200 continue
100 continue
4 Creating Fortran MEX-Files
4-30
C NOTE: Sparse indexing is zero based.
jc(n+1) = k1
loadsparse = 0
300 return
end
C The gateway routine
subroutine mexFunction(nlhs, plhs, nrhs, prhs)
integer nlhs, nrhs
C--------------------------------------------------------------
C (integer) Replace integer by integer*8 on the DEC Alpha and
C the SGI 64-bit platforms.
C
integer plhs(*), prhs(*)
integer mxGetPr, mxCreateSparse, mxGetIr, mxGetJc
integer pr, sr, irs, jcs
C--------------------------------------------------------------
C
integer m, n, nzmax
integer mxGetM, mxGetN, mxIsComplex, mxIsDouble
integer loadsparse
C Check for proper number of arguments.
if (nrhs .ne. 1) then
call mexErrMsgTxt('One input argument required.')
endif
if (nlhs .gt. 1) then
call mexErrMsgTxt('Too many output arguments.')
endif
C Check data type of input argument.
if (mxIsDouble(prhs(1)) .eq. 0) then
call mexErrMsgTxt('Input argument must be of type double.')
endif
if (mxIsComplex(prhs(1)) .eq. 1) then
call mexErrMsgTxt('Input argument must be real only')
endif
C Get the size and pointers to input data.
m = mxGetM(prhs(1))
Examples of Fortran MEX-Files
4-31
n = mxGetN(prhs(1))
pr = mxGetPr(prhs(1))
C Allocate space.
C NOTE: Assume at most 20% of the data is sparse.
nzmax = dble(m*n) *.20 + .5
C NOTE: The maximum number of non-zero elements cannot be less
C than the number of columns in the matrix.
if (n .gt. nzmax) then
nzmax = n
endif
plhs(1) = mxCreateSparse(m, n, nzmax, 0)
sr = mxGetPr(plhs(1))
irs = mxGetIr(plhs(1))
jcs = mxGetJc(plhs(1))
C Load the sparse data.
if
(loadsparse(%val(pr),%val(sr),%val(irs),%val(jcs),m,n,nzmax)
+ .eq. 1) then
call mexPrintf('Truncating output, input is > 20%% sparse')
endif
return
end
At the MATLAB prompt, enteri ng
full = eye(5)
full =
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1
4 Creating Fortran MEX-Files
4-32
creates a ful l , 5-by-5 i denti ty matri x. Usi ng fulltosparse on the ful l matri x
produces the correspondi ng sparse matri x.
spar = fulltosparse(full)
spar =
(1,1) 1
(2,2) 1
(3,3) 1
(4,4) 1
(5,5) 1
Calling MATLAB Functions from Fortran MEX-Files
I ts possi bl e to cal l MATLAB functi ons, operators, M-fi l es, and even other
MEX-fi l es from wi thi n your Fortran source code by usi ng the API functi on
mexCallMATLAB. Thi s exampl e creates an mxArray, passes vari ous poi nters to a
subfuncti on to acqui re data, and cal l s mexCallMATLAB to cal cul ate the si ne
functi on and pl ot the resul ts.
C $Revision: 1.2 $
C
===============================================================
C
C sincall.f
C
C Example for illustrating how to use mexCallMATLAB
C
C Creates an mxArray and passes its associated pointers (in
C this demo, only pointer to its real part, pointer to
C number of rows, pointer to number of columns) to
C subfunction fill() to get data filled up, then calls
C mexCallMATLAB to calculate the sin function and plot the
C result.
C This is a MEX-file for MATLAB.
C Copyright (c) 1984-1998 The MathWorks, Inc.
C
===============================================================
Examples of Fortran MEX-Files
4-33
C Subroutine for filling up data
subroutine fill(pr, m, n, max)
real*8 pr(*)
integer i, m, n, max
m=max/2
n=1
do 10 i=1,m
10 pr(i)=i*(4*3.1415926/max)
return
end
C Gateway subroutine
subroutine mexFunction(nlhs, plhs, nrhs, prhs)
integer nlhs, nrhs
C--------------------------------------------------------------
C (integer) Replace integer by integer*8 on the DEC Alpha
C and the SGI 64-bit platforms.
C
integer plhs(*), prhs(*)
integer rhs(1), lhs(1)
integer mxGetPr, mxCreateFull
C--------------------------------------------------------------
C
integer m, n, max
C Initializition
m=1
n=1
max=1000
rhs(1) = mxCreateFull(max, 1, 0)
4 Creating Fortran MEX-Files
4-34
C Pass the integer and variable and let fill() fill up data.
call fill(%val(mxGetPr(rhs(1))), m, n, max)
call mxSetM(rhs(1), m)
call mxSetN(rhs(1), n)
call mexCallMATLAB(1, lhs, 1, rhs, 'sin')
call mexCallMATLAB(0, NULL, 1, lhs, 'plot')
C Cleanup the unfreed memory after calling mexCallMATLAB.
call mxFreeMatrix(rhs(1))
call mxFreeMatrix(lhs(1))
return
end
I t i s possi bl e to use mexCallMATLAB (or any other API routi ne) from wi thi n your
computati onal Fortran subrouti ne. Note that you can onl y cal l most MATLAB
functi ons wi th doubl e-preci si on data. M-functi ons that perform computati ons,
l i ke eig, wi l l not work correctl y wi th data that i s not doubl e preci si on.
Runni ng thi s exampl e
sincall
Examples of Fortran MEX-Files
4-35
di spl ays the resul ts
Note: I t i s possi bl e to generate an object of type mxUNKNOWN_CLASS usi ng
mexCallMATLAB. For exampl e, i f you create an M-fi l e that returns two
vari abl es but onl y assi gns one of them a val ue,
function [a,b]=foo[c]
a=2*c;
youl l get thi s warni ng message i n MATLAB:
Warning: One or more output arguments not assigned during call
to 'foo'.
I f you then cal l foo usi ng mexCallMATLAB, the unassi gned output vari abl e wi l l
now be of type mxUNKNOWN_CLASS.
4 Creating Fortran MEX-Files
4-36
Advanced Topics
These secti ons cover advanced features of MEX-fi l es that you can use when
your appl i cati ons requi re sophi sti cated MEX-fi l es.
Help Files
Because the MATLAB i nterpreter chooses the MEX-fi l e when both an M-fi l e
and a MEX-fi l e wi th the same name are encountered i n the same di rectory, i t
i s possi bl e to use M-fi l es for documenti ng the behavi or of your MEX-fi l es. The
MATLAB help command wi l l automati cal l y fi nd and di spl ay the appropri ate
M-fi l e when hel p i s requested and the i nterpreter wi l l fi nd and execute the
correspondi ng MEX-fi l e when the functi on i s actual l y i nvoked.
Linking Multiple Files
You can combi ne several source fi l es when bui l di ng MEX-fi l es. For exampl e,
mex circle.f square.o rectangle.f shapes.o
i s a l egal command that operates on the .f and .o fi l es to create a MEX-fi l e
cal l ed circle.ext, where ext i s the extensi on correspondi ng to the MEX-fi l e
type. The name of the resul ti ng MEX-fi l e i s taken from the fi rst fi l e i n the l i st.
You may fi nd i t useful to use a software devel opment tool l i ke MAKE to manage
MEX-fi l e projects i nvol vi ng mul ti pl e source fi l es. Si mpl y create a MAKEFILE
that contai ns a rul e for produci ng object fi l es from each of your source fi l es and
then i nvoke mex to combi ne your object fi l es i nto a MEX-fi l e. Thi s way you can
ensure that your source fi l es are recompi l ed onl y when necessary.
Note: On UNI X, you must use the fortran swi tch to the mex scri pt i f you are
l i nki ng Fortran objects.
Variable Scope
Unl i ke M-fi l e functi ons, MEX-fi l e functi ons do not have thei r own vari abl e
workspace. mexEvalString eval uates the stri ng i n the cal l ers workspace. I n
addi ti on, you can use the mexGetMatrix and mexPutMatrix routi nes to get and
put vari abl es i nto the cal l ers workspace.
Advanced Topics
4-37
Memory Management
MATLAB Versi on 5.2 now i mpl i ci tl y destroys (by cal l i ng mxDestroyArray) any
arrays created by a MEX-fi l e that are not returned i n the l eft-hand si de l i st
(plhs()). Consequentl y, any mi sconstructed arrays l eft over at the end of a
MEX-fi l es executi on have the potenti al to cause memory errors.
I n general , we recommend that MEX-fi l es destroy thei r own temporary arrays
and cl ean up thei r own temporary memory. For addi ti onal i nformati on on
memory management techni ques, see the Memory Management secti on i n
Chapter 3 and the Memory Management Compati bi l i ty I ssues secti on i n
Chapter 8.
4 Creating Fortran MEX-Files
4-38
How to Debug Fortran Language MEX-Files
On most pl atforms, i t i s now possi bl e to debug MEX-fi l es whi l e they are
runni ng wi thi n MATLAB. Compl ete source code debuggi ng, i ncl udi ng setti ng
breakpoi nts, exami ni ng vari abl es, and steppi ng through the source code
l i ne-by-l i ne, i s now avai l abl e.
Note: The secti on, Troubl eshooti ng, i n Chapter 8 provi des addi ti onal
i nformati on on i sol ati ng probl ems wi th MEX-fi l es.
To debug a MEX-fi l e from wi thi n MATLAB, you must fi rst compi l e the
MEX-fi l e wi th the g opti on to mex.
mex g filename.f
Debugging on UNIX
You must start MATLAB from wi thi n a debugger. To do thi s, speci fy the name
of the debugger you want to use wi th the D opti on when starti ng MATLAB.
For exampl e, to use dbx, the UNI X debugger, type
matlab Ddbx
Once the debugger l oads MATLAB i nto memory, you can start i t by i ssui ng a
run command. Now, from wi thi n MATLAB, enabl e MEX-fi l e debuggi ng by
typi ng
dbmex on
at the MATLAB prompt. Then run the MEX-fi l e you want to debug as you
woul d ordi nari l y (ei ther di rectl y or by means of some other functi on or scri pt).
Before executi ng the MEX-fi l e, you wi l l be returned to the debugger.
You may need to tel l the debugger where the MEX-fi l e was l oaded or the name
of the MEX-fi l e, i n whi ch case MATLAB wi l l di spl ay the appropri ate command
for you to use. At thi s poi nt, you are ready to start debuggi ng. You can l i st the
source code for your MEX-fi l e and set break poi nts i n i t. I t i s often conveni ent
How to Debug Fortran Language MEX-Files
4-39
to set one at mexFunction so that you stop at the begi nni ng of the gateway
functi on.
Note: The name mexFunction may be sl i ghtl y al tered by the compi l er (i .e., i t
may have an underscore appended). To determi ne how thi s symbol appears i n
a gi ven MEX-fi l e, use the UNI X command
nm <MEX-file> | grep i mexfunction
To proceed from the breakpoi nt, i ssue a conti nue command to the debugger.
Once you hi t one of your breakpoi nts, you can make ful l use of any faci l i ti es
your debugger provi des to exami ne vari abl es, di spl ay memory, or i nspect
regi sters. Refer to the documentati on provi ded wi th your debugger for
i nformati on on i ts use.
I f you are at the MATLAB prompt and want to return control to the debugger,
you can i ssue the command
dbmex stop
whi ch al l ows you to gai n access to the debugger so you can set addi ti onal
breakpoi nts or exami ne source code. To resume executi on, i ssue a conti nue
command to the debugger.
Debugging on Windows
DIGITAL Visual Fortran. I f you are usi ng the DI GI TAL Vi sual Fortran compi l er,
you use the Mi crosoft debuggi ng envi ronment to debug your program.
1 Start the Mi crosoft Vi sual Studi o by typi ng at the DOS prompt
msdev filename.dll
2 I n the Mi crosoft envi ronment, from the Project menu, sel ect Settings. I n
the wi ndow that opens, sel ect the Debugtab. Thi s opti ons wi ndow contai ns
4 Creating Fortran MEX-Files
4-40
edi t boxes. I n the edi t box l abel ed Executablefor debugsession, enter the
ful l path where MATLAB 5 resi des. Al l other edi t boxes shoul d be empty.
3 Open the source fi l es and set a break poi nt on the desi red l i ne of code by
ri ght-cl i cki ng wi th your mouse on the l i ne of code.
4 From the Build menu, sel ect Debug, and cl i ck Go.
5 You wi l l now be abl e to run your MEX-fi l e i n MATLAB and use the Mi crosoft
debuggi ng envi ronment. For more i nformati on on how to debug i n the
Mi crosoft envi ronment, see the Mi crosoft Devel opment Studi o
documentati on.
5
Data Export and I mport
UsingMAT-Files . . . . . . . . . . . . . . . . . . 5-2
I mporti ng Data to MATLAB . . . . . . . . . . . . . . 5-2
Exporti ng Data from MATLAB . . . . . . . . . . . . . 5-3
Exchangi ng Data Fi l es Between Pl atforms . . . . . . . . 5-4
Readi ng and Wri ti ng MAT-Fi l es . . . . . . . . . . . . 5-4
Di rectory Organi zati on . . . . . . . . . . . . . . . . 5-7
Examples of MAT-Files . . . . . . . . . . . . . . . 5-10
Creati ng a MAT-Fi l e . . . . . . . . . . . . . . . . . 5-10
Readi ng a MAT-Fi l e . . . . . . . . . . . . . . . . . 5-19
Compilingand LinkingMAT-FilePrograms . . . . . . 5-28
Speci al Consi derati ons . . . . . . . . . . . . . . . . 5-28
UNI X . . . . . . . . . . . . . . . . . . . . . . . 5-29
Wi ndows . . . . . . . . . . . . . . . . . . . . . . 5-31
5 Data Export and Import
5-2
Using MAT-Files
Thi s secti on descri bes the vari ous techni ques for i mporti ng data to and
exporti ng data from the MATLAB envi ronment. The most i mportant approach
i nvol ves the use of MAT-fi l es the data fi l e format that MATLAB uses for
savi ng data to your di sk. MAT-fi l es provi de a conveni ent mechani sm for
movi ng your MATLAB data between di fferent pl atforms and for i mporti ng and
exporti ng your data to other stand-al one MATLAB appl i cati ons. To si mpl i fy
your use of MAT-fi l es i n appl i cati ons outsi de of MATLAB, we have devel oped
a l i brary of access routi nes wi th a mat prefi x that you can use i n your own C or
Fortran programs to read and wri te MAT-fi l es. Programs that access MAT-fi l es
al so use the mx prefi xed API routi nes di scussed i n the Creati ng C Language
MEX-Fi l es and Creati ng Fortran MEX-Fi l es chapters of thi s book.
Thi s chapter i ncl udes these topi cs:
I mporti ng and exporti ng data to and from MATLAB
Exchangi ng data fi l es between pl atforms
Readi ng from and wri ti ng to MAT-fi l es
Compi l i ng and l i nki ng MAT-fi l e programs
Importing Data to MATLAB
You can i ntroduce data from other programs i nto MATLAB by several
methods. The best method for i mporti ng data depends on how much data there
i s, whether the data i s al ready i n machi ne-readabl e form, and what format the
data i s i n. Here are some choi ces; sel ect the one that best meets your needs.
Enter the data as an expl i ci t l i st of el ements. I f you have a smal l amount of
data, l ess than 10-15 el ements, i t i s easy to type the data expl i ci tl y usi ng
brackets [ ]. Thi s method i s awkward for l arger amounts of data because you
cant edi t your i nput i f you make a mi stake.
Create data i n an M-fi l e. Use your text edi tor to create an M-fi l e that enters
your data as an expl i ci t l i st of el ements. Thi s method i s useful when the data
i snt al ready i n computer-readabl e form and you have to type i t i n.
Essenti al l y the same as the fi rst method, thi s method has the advantage of
Using MAT-Files
5-3
al l owi ng you to use your edi tor to change the data and correct mi stakes. You
can then just rerun your M-fi l e to re-enter the data.
Load data from an ASCI I fl at fi l e. A flat filestores the data i n ASCI I form,
wi th fi xed-l ength rows termi nated wi th new l i nes (carri age returns) and
wi th spaces separati ng the numbers. You can edi t ASCI I fl at fi l es usi ng a
normal text edi tor. Fl at fi l es can be read di rectl y i nto MATLAB usi ng the
load command. The resul t i s to create a vari abl e wi th the same name as the
fi l ename.
Read data usi ng fopen, fread, and MATLABs other l ow-l evel I /O functi ons.
Thi s method i s useful for l oadi ng data fi l es from other appl i cati ons that have
thei r own establ i shed fi l e formats.
Wri te a MEX-fi l e to read the data. Thi s i s the method of choi ce i f subrouti nes
are al ready avai l abl e for readi ng data fi l es from other appl i cati ons. See the
secti on, I ntroduci ng MEX-Fi l es, i n Chapter 2 for more i nformati on.
Wri te a program i n C or Fortran to transl ate your data i nto MAT-fi l e format
and then read the MAT-fi l e i nto MATLAB wi th the load command. Refer to
the secti on, Readi ng and Wr i ti ng MAT-Fi l es, for mor e i nformati on.
Exporting Data from MATLAB
There are several methods for getti ng MATLAB data back to the outsi de worl d:
For smal l matri ces, use the diary command to create a di ary fi l e and di spl ay
the vari abl es, echoi ng them i nto thi s fi l e. You can use your text edi tor to
mani pul ate the di ary fi l e at a l ater ti me. The output of diary i ncl udes the
MATLAB commands used duri ng the sessi on, whi ch i s useful for i ncl usi on
i nto documents and reports.
Save the data i n ASCI I form usi ng the save command wi th the ascii
opti on. For exampl e,
A = rand(4,3);
save temp.dat A ascii
creates an ASCI I fi l e cal l ed temp.dat contai ni ng:
1.3889088e001 2.7218792e001 4.4509643e001
2.0276522e001 1.9881427e001 9.3181458e001
1.9872174e001 1.5273927e002 4.6599434e001
6.0379248e001 7.4678568e001 4.1864947e001
5 Data Export and Import
5-4
The ascii opti on supports data i n numeri cal matri x form onl y; numeri cal
arrays (more than 2-di mensi ons), cel l arrays, and structures are not
supported.
Wri te the data i n a speci al format usi ng fopen, fwrite, and the other
l ow-l evel I /O functi ons. Thi s method i s useful for wri ti ng data fi l es i n the fi l e
formats requi red by other appl i cati ons.
Devel op a MEX-fi l e to wri te the data. Thi s i s the method of choi ce i f
subrouti nes are al ready avai l abl e for wri ti ng data fi l es i n the form needed by
other appl i cati ons. See the secti on, I ntroduci ng MEX-Fi l es, i n Chapter 2
for more i nformati on.
Wri te out the data as a MAT-fi l e usi ng the save command, and then wri te a
program i n C or Fortran to transl ate the MAT-fi l e i nto your own speci al
format. See the secti on, Readi ng and Wri ti ng MAT-Fi l es, for more
i nformati on.
Exchanging Data Files Between Platforms
You may want to work wi th MATLAB i mpl ementati ons on several di fferent
computer systems, or need to transmi t MATLAB appl i cati ons to users on other
systems. MATLAB appl i cati ons consi st of M-fi l es contai ni ng functi ons and
scri pts, and MAT-fi l es contai ni ng bi nary data. Both types of fi l es can be
transported di rectl y between machi nes: M-fi l es because they are pl atform
i ndependent and MAT-fi l es because they contai n a machi ne si gnature i n the
fi l e header. MATLAB checks the si gnature when i t l oads a fi l e and, i f a
si gnature i ndi cates that a fi l e i s forei gn, performs the necessary conversi on.
Usi ng MATLAB across several di fferent machi ne archi tectures requi res a
faci l i ty for exchangi ng both bi nary and ASCI I data between the vari ous
machi nes. Exampl es of thi s type of faci l i ty i ncl ude FTP, NFS, Kermi t, and
other communi cati on programs. When usi ng these programs, be careful to
transmi t bi nary MAT-fi l es i n binaryfilemodeand ASCI I M-fi l es i n ASCI I file
mode. Fai l ure to set these modes correctl y corrupts the data.
Reading and Writing MAT-Files
The save command i n MATLAB saves the MATLAB arrays currentl y i n
memory to a bi nary di sk fi l e cal l ed a MAT-fi l e. The term MAT-fi l e i s used
because these fi l es have the extensi on .mat. The load command performs the
Using MAT-Files
5-5
reverse operati on: i t reads the MATLAB arrays from a MAT-fi l e on di sk back
i nto MATLABs workspace.
A MAT-fi l e may contai n one or more of any of the data types supported i n
MATLAB 5, i ncl udi ng stri ngs, matri ces, mul ti di mensi onal arrays, structures,
and cel l arrays. MATLAB wri tes the data sequenti al l y onto di sk as a
conti nuous byte stream.
MAT-File Interface Library
The MAT-fi l e i nterface l i brary contai ns a set of subrouti nes for readi ng and
wri ti ng MAT-fi l es. You can cal l these routi nes from wi thi n your own C and
Fortran programs. We recommend that you use these routi nes, rather than
attempt to wri te your own code, to perform these operati ons. By usi ng the
routi nes i n thi s l i brary, you wi l l be i nsul ated from future changes to the
MAT-fi l e structure.
The MAT-fi l e l i brary contai ns routi nes for readi ng and wri ti ng MAT-fi l es. They
al l begi n wi th the three-l etter prefi x mat. These tabl es l i st al l the avai l abl e
MAT-functi ons and thei r purposes.
Table 5-1: C MAT-File Routines
MAT-Function Purpose
matOpen Open a MAT-fi l e
matClose Cl ose a MAT-fi l e
matGetDir Get a l i st of MATLAB arrays from a
MAT-fi l e
matGetFp Get an ANSI C fi l e poi nter to a MAT-fi l e
matGetArray Read a MATLAB array from a MAT-fi l e
matPutArray Wri te a MATLAB array to a MAT-fi l e
matGetNextArray Read the next MATLAB array from a
MAT-fi l e
matDeleteArray Remove a MATLAB array from a MAT-fi l e
5 Data Export and Import
5-6
matPutArrayAsGlobal Put a MATLAB array i nto a MAT-fi l e such
that the load command wi l l pl ace i t i nto
the gl obal workspace
matGetArrayHeader Load a MATLAB array header from a
MAT-fi l e (no data)
matGetNextArrayHeader Load the next MATLAB array header
from a MAT-fi l e (no data)
Table 5-2: Fortran MAT-File Routines
MAT-Function Purpose
matOpen Open a MAT-fi l e
matClose Cl ose a MAT-fi l e
matGetDir Get a l i st of MATLAB arrays from a
MAT-fi l e
matGetMatrix Get a named MATLAB array from a
MAT-fi l e
matPutMatrix Put a MATLAB array i nto a MAT-fi l e
matGetNextMatrix Get the next sequenti al MATLAB array
from a MAT-fi l e
matDeleteMatrix Remove a MATLAB array from a MAT-fi l e
matGetString Read a MATLAB stri ng from a MAT-fi l e
matPutString Wri te a MATLAB stri ng to a MAT-fi l e
Table 5-1: C MAT-File Routines (Continued)
MAT-Function Purpose
Using MAT-Files
5-7
Directory Organization
A col l ecti on of fi l es associ ated wi th readi ng and wri ti ng MAT-fi l es i s l ocated on
your di sk. Tabl e 5-3 l i sts the path to the requi red subdi rectori es for i mporti ng
and exporti ng data usi ng MAT-functi ons.
The include di rectory hol ds header fi l es contai ni ng functi on decl arati ons wi th
prototypes for the routi nes that you can access i n the API Li brary. I ncl uded i n
the subdi rectory are:
matrix.h, the header fi l e that defi nes MATLAB array access and creati on
methods
mat.h, the header fi l e that defi nes MAT-fi l e access and creati on methods
The subdi rectory that contai ns shared (dynami cal l y l i nkabl e) l i brari es for
l i nki ng your programs i s pl atform dependent.
Table 5-3: MAT-Function Subdirectories
Platform Contents Directories
Wi ndows I ncl ude Fi l es <matlab>\extern\include
Li brari es <matlab>\bin
Exampl es <matlab>\extern\examples/eng_mat
UNI X I ncl ude Fi l es <matlab>/extern/include
Li brari es <matlab>/extern/lib/$arch
Exampl es <matlab>/extern/examples/eng_mat
5 Data Export and Import
5-8
Windows
The bin subdi rectory contai ns the shared l i brari es for l i nki ng your programs.
UNIX
The extern/lib/$arch subdi rectory, where $arch i s your machi nes
archi tecture, contai ns the shared l i brari es for l i nki ng your programs. For
exampl e, on sol2, the subdi rectory i s extern/lib/sol2.
so refers to the shared l i brary extensi on for your pl atform. For exampl e, on
sol2, these fi l es are libmat.so and libmx.so.
Table 5-4: Shared Libraries on Windows
Library Description
libmat.dll The l i brary of MAT-fi l e routi nes (C and
Fortran)
libmx.dll The l i brary of array access and creati on
routi nes
Table 5-5: Shared Libraries on UNIX
Library Description
libmat.so The l i brary of MAT-fi l e routi nes (C and
Fortran)
libmx.so The l i brary of array access and creati on
routi nes
Using MAT-Files
5-9
Example Files
The examples/eng_mat subdi rectory contai ns C and Fortran source code for a
number of exampl e fi l es that demonstrate how to use the MAT-fi l e routi nes.
For addi ti onal i nformati on about the MATLAB API di rectory organi zati on, see
Appendi x B, Di rectory Organi zati on.
Table 5-6: C and Fortran Examples
Library Description
matcreat.c Exampl e C program that demonstrates
how to use the l i brary routi nes to create a
MAT-fi l e that can be l oaded i nto MATLAB
matdgns.c Exampl e C program that demonstrates
how to use the l i brary routi nes to read and
di agnose a MAT-fi l e
matdemo1.f Exampl e Fortran program that
demonstrates how to cal l the MATLAB
MAT-fi l e functi ons from a Fortran
program
matdemo2.f Exampl e Fortran program that
demonstrates how to use the l i brary
routi nes to read i n the MAT-fi l e created by
matdemo1.f and descri be i ts contents
5 Data Export and Import
5-10
Examples of MAT-Files
Thi s secti on i ncl udes C and Fortran exampl es of wri ti ng, readi ng, and
di agnosi ng MAT-fi l es.
Creating a MAT-File
C Example
Thi s sampl e program i l l ustrates how to use the l i brary routi nes to create a
MAT-fi l e that can be l oaded i nto MATLAB.
/* $Revision: 1.2 $ */
/*
* MAT-file creation program
*
* Calling syntax:
*
* matcreat
*
* Create a MAT-file that can be loaded into MATLAB.
*
* This program demonstrates the use of the following functions:
*
* matClose
* matGetArray
* matOpen
* matPutArray
* matPutArrayAsGlobal
* Copyright (c) 1984-1998 The MathWorks, Inc.
*/
#include <stdio.h>
#include <stdlib.h>
#include "string.h"
#include "mat.h"
#define BUFSIZE 255
Examples of MAT-Files
5-11
int create(const char *file) {
MATFile *pmat;
mxArray *pa1, *pa2, *pa3;
double data[9] = { 1.0, 4.0, 7.0, 2.0, 5.0, 8.0, 3.0, 6.0, 9.0 };
char str[BUFSIZE];
printf("Creating file %s...\n\n", file);
pmat = matOpen(file, "w");
if (pmat == NULL) {
printf("Error creating file %s\n", file);
printf("(do you have write permission in this directory?)\n");
return(1);
}
pa1 = mxCreateDoubleMatrix(3,3,mxREAL);
mxSetName(pa1, "LocalDouble");
pa2 = mxCreateDoubleMatrix(3,3,mxREAL);
mxSetName(pa2, "GlobalDouble");
memcpy((void *)(mxGetData(pa2)), (void *)data,
3*3*sizeof(double));
pa3 = mxCreateString("MATLAB: the language of technical
computing");
mxSetName(pa3, "LocalString");
matPutArray(pmat, pa1);
matPutArrayAsGlobal(pmat, pa2);
matPutArray(pmat, pa3);
/*
* Ooops! We need to copy data before writing the array. (Well,
* ok, this was really intentional.) This demonstrates that
* matPutArray will overwrite an existing array in a MAT-file.
*/
memcpy((char *)(mxGetPr(pa1)), (char *)data,
3*3*sizeof(double));
matPutArray(pmat, pa1);
5 Data Export and Import
5-12
/* Clean up. */
mxDestroyArray(pa1);
mxDestroyArray(pa2);
mxDestroyArray(pa3);
if (matClose(pmat) != 0) {
printf("Error closing file %s\n",file);
return(1);
}
/*
* Reopen file and verify its contents with matGetArray.
*/
pmat = matOpen(file, "r");
if (pmat == NULL) {
printf("Error reopening file %s\n", file);
return(1);
}
/*
* Read in each array we just wrote.
*/
pa1 = matGetArray(pmat, "LocalDouble");
if (pa1 == NULL) {
printf("Error reading existing matrix LocalDouble\n");
return(1);
}
if (mxGetNumberOfDimensions(pa1) != 2) {
printf("Error saving matrix: result does not have two
dimensions\n");
return(1);
}
pa2 = matGetArray(pmat, "GlobalDouble");
if (pa2 == NULL) {
printf("Error reading existing matrix LocalDouble\n");
return(1);
}
Examples of MAT-Files
5-13
if (!(mxIsFromGlobalWS(pa2))) {
printf("Error saving global matrix: result is not global\n");
return(1);
}
pa3 = matGetArray(pmat, "LocalString");
if (pa3 == NULL) {
printf("Error reading existing matrix LocalDouble\n");
return(1);
}
mxGetString(pa3, str, BUFSIZE);
if (strcmp(str, "MATLAB: the language of technical computing"))
{
printf("Error saving string: result has incorrect
contents\n");
return(1);
}
/* Clean up before exit. */
mxDestroyArray(pa1);
mxDestroyArray(pa2);
mxDestroyArray(pa3);
if (matClose(pmat) != 0) {
printf("Error closing file %s\n",file);
return(1);
}
printf("Done\n");
return(0);
}
int main()
{
int result;
result = create("mattest.mat");
return (result==0)?EXIT_SUCCESS:EXIT_FAILURE;
}
5 Data Export and Import
5-14
To produce an executabl e versi on of thi s exampl e program, compi l e the fi l e and
l i nk i t wi th the appropri ate l i brary. Detai l s on how to compi l e and l i nk
MAT-fi l e programs on the vari ous pl atforms are di scussed i n the Compi l i ng
and Li nki ng MAT-Fi l e Programs secti on.
Once you have compi l ed and l i nked your MAT-fi l e program, you can run the
stand-al one appl i cati on you have just produced. Thi s program creates a
MAT-fi l e, mattest.mat, that can be l oaded i nto MATLAB. To run the
appl i cati on, dependi ng on your pl atform, ei ther doubl e-cl i ck on i ts i con or enter
matcreat at the system prompt.
matcreat
Creating file mattest.mat...
To veri fy that the MAT-fi l e has been created, at the MATLAB prompt enter
whos file mattest.mat
Name Size Bytes Class
GlobalDouble 3x3 72 double array (global)
LocalDouble 3x3 72 double array
LocalString 1x43 86 char array
Grand total is 61 elements using 230 bytes
Fortran Example
Thi s exampl e creates a MAT-fi l e, matdemo.mat.
C $Revision: 1.1 $
C
C matdemo1.f
C
C This is a simple program that illustrates how to call the
C MATLAB MAT-file functions from a Fortran program. This
C demonstration focuses on writing MAT-files.
C
C Copyright (c) 1984-1998 The MathWorks, Inc.
C All rights reserved
C
Examples of MAT-Files
5-15
C
C matdemo1 - Create a new MAT-file from scratch.
C
program matdemo1
C--------------------------------------------------------------
C (integer) Replace integer by integer*8 on the DEC alpha
C and the SGI64 platforms.
C
integer matOpen, mxCreateFull, mxCreateString
integer matGetMatrix, mxGetPr
integer mp, pa1, pa2, pa3
C--------------------------------------------------------------
C
C Other variable declarations here
C
integer status, matClose
double precision dat(9)
data dat / 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0 /
C
C Open MAT-file for writing.
C
write(6,*) 'Creating MAT-file matdemo.mat ...'
mp = matOpen('matdemo.mat', 'w')
if (mp .eq. 0) then
write(6,*) 'Can''t open ''matdemo.mat'' for writing.'
write(6,*) '(Do you have write permission in this directory?)'
stop
end if
C
C Create variables.
C
pa1 = mxCreateFull(3,3,0)
call mxSetName(pa1, 'Numeric')
C
pa2 = mxCreateString('MATLAB: The language of computing')
call mxSetName(pa2, 'String')
C
5 Data Export and Import
5-16
pa3 = mxCreateString('MATLAB: The language of computing')
call mxSetName(pa3, 'String2')
C
call matPutMatrix(mp, pa1)
call matPutMatrix(mp, pa2)
call matPutMatrix(mp, pa3)
C
C Whoops! Forgot to copy the data into the first matrix --
C it's now blank. (Well, ok, this was deliberate.) This
C demonstrates that matPutMatrix will overwrite existing
C matrices.
C
call mxCopyReal8ToPtr(dat, mxGetPr(pa1), 9)
call matPutMatrix(mp, pa1)
C
C Now, we'll delete String2 from the MAT-file.
C
call matDeleteMatrix(mp, 'String2')
C
C Finally, read back in MAT-file to make sure we know what we
C put in it.
C
status = matClose(mp)
if (status .ne. 0) then
write(6,*) 'Error closing MAT-file'
stop
end if
C
mp = matOpen('matdemo.mat', 'r')
if (status .ne. 0) then
write(6,*) 'Can''t open ''matdemo.mat'' for reading.'
stop
end if
C
pa1 = matGetMatrix(mp, 'Numeric')
if (mxIsNumeric(pa1) .eq. 0) then
write(6,*) 'Invalid non-numeric matrix written to MAT-file'
stop
end if
Examples of MAT-Files
5-17
C
pa2 = matGetMatrix(mp, 'String')
if (mxIsString(pa2) .eq. 0) then
write(6,*) 'Invalid non-numeric matrix written to MAT-file'
stop
end if
C
pa3 = matGetMatrix(mp, 'String2')
if (pa3 .ne. 0) then
write(6,*) 'String2 not deleted from MAT-file'
stop
end if
C
status = matClose(mp)
if (status .ne. 0) then
write(6,*) 'Error closing MAT-file'
stop
end if
C
write(6,*) 'Done creating MAT-file'
stop
end
Once you have compi l ed and l i nked your MAT-fi l e program, you can run the
stand-al one appl i cati on you have just produced. Thi s program creates a
MAT-fi l e, matdemo.mat, that can be l oaded i nto MATLAB. To run the
appl i cati on, dependi ng on your pl atform, ei ther doubl e-cl i ck on i ts i con or enter
matdemo1 at the system prompt.
matdemo1
Creating MAT-file matdemo.mat ...
Done creating MAT-file
5 Data Export and Import
5-18
To veri fy that the MAT-fi l e has been created, at the MATLAB prompt enter
whos file matdemo.mat
Name Size Bytes Class
Numeric 3x3 72 double array
String 1x33 66 char array
Grand total is 42 elements using 138 bytes
Note: For an exampl e of a Wi ndows stand-al one program (not MAT-fi l e
speci fi c), see engwindemo.c i n the <matlab>\extern\examples\eng_mat
di rectory.
Examples of MAT-Files
5-19
Reading a MAT-File
C Example
Thi s sampl e program i l l ustrates how to use the l i brary routi nes to read and
di agnose a MAT-fi l e.
/* $Revision: 1.1 $ */
/*
* MAT-file diagnose program
*
* Calling syntax:
*
* matdgns <matfile.mat>
*
* It diagnoses the MAT-file named <matfile.mat>.
*
* This program demonstrates the use of the following functions:
*
* matClose
* matGetDir
* matGetNextArray
* matGetNextArrayHeader
* matOpen
*
* Copyright (c) 1984-1998 The MathWorks, Inc.
*/
#include <stdio.h>
#include <stdlib.h>
#include "string.h"
#include "mat.h"
int diagnose(const char *file) {
MATFile *pmat;
char **dir;
int ndir;
int i;
mxArray *pa;
5 Data Export and Import
5-20
printf("Reading file %s...\n\n", file);
/*
* Open file to get directory.
*/
pmat = matOpen(file, "r");
if (pmat == NULL) {
printf("Error opening file %s\n", file);
return(1);
}
/*
* Get directory of MAT-file.
*/
dir = matGetDir(pmat, &ndir);
if (dir == NULL) {
printf("Error reading directory of file %s\n", file);
return(1);
} else {
printf("Directory of %s:\n", file);
for (i=0; i < ndir; i++)
printf("%s\n",dir[i]);
}
mxFree(dir);
/* In order to use matGetNextXXX correctly, reopen file to read
in headers. */
if (matClose(pmat) != 0) {
printf("Error closing file %s\n",file);
return(1);
}
pmat = matOpen(file, "r");
if (pmat == NULL) {
printf("Error reopening file %s\n", file);
return(1);
}
Examples of MAT-Files
5-21
/* Get headers of all variables. */
printf("\nExamining the header for each variable:\n");
for (i=0; i < ndir; i++) {
pa = matGetNextArrayHeader(pmat);
if (pa == NULL) {
printf("Error reading in file %s\n", file);
return(1);
}
/* Diagnose header pa. */
printf("According to its header, array %s has %d
dimensions\n", mxGetName(pa),
mxGetNumberOfDimensions(pa));
if (mxIsFromGlobalWS(pa))
printf(" and was a global variable when saved\n");
else
printf(" and was a local variable when saved\n");
mxDestroyArray(pa);
}
/* Reopen file to read in actual arrays. */
if (matClose(pmat) != 0) {
printf("Error closing file %s\n",file);
return(1);
}
pmat = matOpen(file, "r");
if (pmat == NULL) {
printf("Error reopening file %s\n", file);
return(1);
}
/* Read in each array. */
printf("\nReading in the actual array contents:\n");
for (i=0; i<ndir; i++) {
pa = matGetNextArray(pmat);
if (pa == NULL) {
printf("Error reading in file %s\n", file);
return(1);
}
5 Data Export and Import
5-22
/*
* Diagnose array pa.
*/
printf("According to its contents, array %s has %d
dimensions\n", mxGetName(pa),
mxGetNumberOfDimensions(pa));
if (mxIsFromGlobalWS(pa))
printf(" and was a global variable when saved\n");
else
printf(" and was a local variable when saved\n");
mxDestroyArray(pa);
}
if (matClose(pmat) != 0) {
printf("Error closing file %s\n",file);
return(1);
}
printf("Done\n");
return(0);
}
int main(int argc, char **argv)
{
int result;
if (argc > 1)
result = diagnose(argv[1]);
else{
result = 0;
printf("Usage: matdgns <matfile>");
printf("where <matfile> is the name of the MAT-file");
printf("to be diagnosed");
}
return (result==0)?EXIT_SUCCESS:EXIT_FAILURE;
}
Examples of MAT-Files
5-23
After compi l i ng and l i nki ng thi s program, you can vi ew i ts resul ts.
matdgns mattest.mat
Reading file mattest.mat...
Directory of mattest.mat:
GlobalDouble
LocalString
LocalDouble
Examining the header for each variable:
According to its header, array GlobalDouble has 2 dimensions
and was a global variable when saved
According to its header, array LocalString has 2 dimensions
and was a local variable when saved
According to its header, array LocalDouble has 2 dimensions
and was a local variable when saved
Reading in the actual array contents:
According to its contents, array GlobalDouble has 2 dimensions
and was a global variable when saved
According to its contents, array LocalString has 2 dimensions
and was a local variable when saved
According to its contents, array LocalDouble has 2 dimensions
and was a local variable when saved
Done
5 Data Export and Import
5-24
Fortran Example
Thi s sampl e program i l l ustrates how to use the l i brary routi nes to read i n the
MAT-fi l e created by matdemo1.f and descri be i ts contents.
C matdemo2.f
C
C This is a simple program that illustrates how to call the
C MATLAB MAT-file functions from a Fortran program. This
C demonstration focuses on reading MAT-files. It reads in
C the MAT-file created by matdemo1.f and describes its
C contents.
C
C Copyright (c) 1996-1998 The MathWorks, Inc.
C All rights reserved
C--------------------------------------------------------------
C $Revision: 1.4 $
C
program matdemo2
C--------------------------------------------------------------
C (integer) Replace integer by integer*8 on the DEC alpha
C and the SGI64 platforms.
C
integer matOpen, matGetDir, matGetNextMatrix
integer mp, dir, adir(100), pa
C--------------------------------------------------------------
C
C Other variable declarations here
C
integer mxGetM, mxGetN, matClose
integer ndir, i, stat
character*32 names(100), name, mxGetName
C
C-------------------------------------------------------------
C Open file and read directory.
C-------------------------------------------------------------
Examples of MAT-Files
5-25
C
mp = matOpen('matdemo.mat', 'r')
if (mp .eq. 0) then
write(6,*) 'Can''t open ''matdemo.mat''.'
stop
end if
C
C Read directory.
C
dir = matgetdir(mp, ndir)
if (dir .eq. 0) then
write(6,*) 'Can''t read directory.'
stop
endif
C
C Copy integer into an array of pointers.
C
call mxCopyPtrToPtrArray(dir, adir, ndir)
C
C Copy integer to character string
C
do 20 i=1,ndir
call mxCopyPtrToCharacter(adir(i), names(i), 32)
20 continue
C
write(6,*) 'Directory of Mat-file:'
do 30 i=1,ndir
write(6,*) names(i)
30 continue
C
stat = matClose(mp)
if (stat .ne. 0) then
write(6,*) 'Error closing ''matdemo.mat''.'
stop
end if
5 Data Export and Import
5-26
C
C-------------------------------------------------------------
C Reopen file and read full arrays.
C-------------------------------------------------------------
C
mp = matOpen('matdemo.mat', 'r')
if (mp .eq. 0) then
write(6,*) 'Can''t open ''matdemo.mat''.'
stop
end if
C
C Read directory.
C
write(6,*) 'Getting full array contents:'
pa = matGetNextMatrix(mp)
do while (pa .ne. 0)
C
C Copy name to character string.
C
name = mxGetName(pa)
write(6,*) 'Retrieved ', name
write(6,*) ' With size ', mxGetM(pa), '-by-', mxGetN(pa)
pa = matGetNextMatrix(mp)
end do
C
stat = matClose(mp)
if (stat .ne. 0) then
write(6,*) 'Error closing ''matdemo.mat''.'
stop
end if
stop
C
end
Examples of MAT-Files
5-27
After compi l i ng and l i nki ng thi s program, you can vi ew i ts resul ts.
matdemo2
Directory of Mat-file:
String
Numeric
Getting full array contents:
1
Retrieved String
With size 1by 33
3
Retrieved Numeric
With size 3by 3
5 Data Export and Import
5-28
Compiling and Linking MAT-File Programs
Thi s secti on descri bes the steps requi red to compi l e and l i nk MAT-fi l e
programs on UNI X and Wi ndows systems. I t begi ns by l ooki ng at a speci al
consi derati on for compi l ers that do not mask fl oati ng-poi nt excepti ons.
Special Considerations
Floating-Point Exceptions
Certai n mathemati cal operati ons can resul t i n nonfi ni te val ues. For exampl e,
di vi si on by zero resul ts i n the nonfi ni te I EEE val ue, inf. A fl oati ng-poi nt
excepti on occurs when such an operati on i s performed. Because MATLAB uses
an I EEE model that supports nonfi ni te val ues such as inf and NaN, MATLAB
di sabl es, or masks, fl oati ng-poi nt excepti ons.
Some compi l ers do not mask fl oati ng-poi nt excepti ons by defaul t. Thi s causes
MAT-fi l e appl i cati ons bui l t wi th such compi l ers to termi nate when a
fl oati ng-poi nt excepti on occurs. Consequentl y, you need to take speci al
precauti ons when usi ng these compi l ers to mask fl oati ng-poi nt excepti ons so
that your MAT-fi l e appl i cati on wi l l perform properl y.
Note: MATLAB-based appl i cati ons shoul d never get fl oati ng-poi nt
excepti ons. I f you do get a fl oati ng-poi nt excepti on, veri fy that any thi rd party
l i brari es that you l i nk agai nst do not enabl e fl oati ng-poi nt excepti on handl i ng.
Thi s tabl e shows the pl atforms and compi l ers on whi ch you shoul d mask
fl oati ng-poi nt excepti ons.
Platform Compiler
DEC Al pha DI GI TAL Fortran 77
Li nux Absoft Fortran
Wi ndows Borl and C++
Compiling and Linking MAT-File Programs
5-29
DEC Alpha. To mask fl oati ng-poi nt excepti ons on the DEC Al pha pl atform, use
the fpe3 compi l e fl ag. For exampl e,
f77 fpe3
Absoft Fortran Compiler on Linux. To mask fl oati ng-poi nt excepti ons when usi ng
the Absoft Fortran compi l er on the Li nux pl atform, you must add some code to
your program. I ncl ude the fol l owi ng at the begi nni ng of your main() program,
before any cal l s to MATLAB API functi ons.
integer cw, arm387
C
cw = arm387(z'0000003F')
cw = cw .or. z'0000003F'
call arm387(cw)
Borland C++ Compiler on Windows. To mask fl oati ng-poi nt excepti ons when usi ng
the Borl and C++ compi l er on the Wi ndows pl atform, you must add some code
to your program. I ncl ude the fol l owi ng at the begi nni ng of your main() or
WinMain() functi on, before any cal l s to MATLAB API functi ons.
#include <float.h>
.
.
.
_control87(MCW_EM,MCW_EM);
.
.
.
UNIX
Under UNI X at runti me, you must tel l the system where the API shared
l i brari es resi de. These secti ons provi de the necessary UNI X commands
dependi ng on your shel l and system archi tecture.
Setting Runtime Library Path
I n C shel l , the command to set the l i brary path i s
setenv LD_LIBRARY_PATH <matlab>/extern/lib/$Arch:$LD_LIBRARY_PATH
5 Data Export and Import
5-30
I n Bourne shel l , the commands to set the l i brary path are
LD_LIBRARY_PATH=<matlab>/extern/lib/$Arch:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH
where:
<matlab> i s the MATLAB root di rectory and $Arch i s your system archi tecture
(alpha, lnx86, sgi, sol2, sun4, hp700, ibm_rs, or sgi64). Note that the
envi ronment vari abl e (LD_LIBRARY_PATH i n thi s exampl e) vari es on several
pl atforms. Tabl e 5-7 l i sts the di fferent envi ronment vari abl e names you shoul d
use on these systems.
I t i s conveni ent to pl ace these commands i n a startup scri pt such as ~/.cshrc
for C shel l or ~/.profile for Bourne shel l .
Compiling and Linking Commands
Tabl e 5-8 provi des the commands requi red to compi l e and l i nk MAT-fi l e C and
Fortran programs on UNI X pl atforms.
Table 5-7: Environment Variables Name
Architecture Environment Variable
HP700 SHLIB_PATH
I BM RS/6000 LIBPATH
SGI 64 LD_LIBRARY64_PATH
Table 5-8: Compiling and Linking MAT-File Programs
UNIX C Command
HP700 cc Aa <include dir> o <result> <source> <libdir> <libraries>
SGI 64 cc 64 mips4 <include dir> o <result> <source> <libdir> <libraries>
Li nux gcc ansi <include dir> o <result> <source> <libdir> <libraries>
SunOS 4.x acc <include dir> o <result> <source> <libdir> <libraries>
Al l others cc <include dir> o <result> <source> <libdir> <libraries>
Compiling and Linking MAT-File Programs
5-31
Special Consideration for Fortran (f77) on HP-UX 10.x
I n the versi on of the Fortran compi l er (f77) that shi ps wi th HP-UX 10.x, the
meani ng of the L fl ag has changed. The L fl ag now requests a l i sti ng. So, to
force the l i nker to see the l i brari es you want l i nked i n wi th your code, use
f77 <include dir> o <result> <source> Wl,L<matlab>/extern/lib/hp700 <libraries>
Windows
To compi l e and l i nk Fortran or C MAT-fi l e programs, use the mex scri pt wi th a
MATopti ons fi l e. The fi l e, df50engmatopts.bat (DI GI TAL Vi sual Fortran), i s
for stand-al one Fortran MAT programs. The fi l es, watengmatopts.bat,
wat11engmatopts.bat, bccengmatopts.bat, msvc50engmatopts.bat, and
msvcengmatopts.bat are for stand-al one C MATprograms. You can fi nd al l of
these fi l es i n <matlab>\bin. Refer to them for detai l s on how to customi ze a
MAT opti ons fi l e for your parti cul ar compi l er.
As an exampl e, to compi l e and l i nk a stand-al one MATappl i cati on on Wi ndows
usi ng MSVC (Versi on 5.0) use
mex f <matlab>\bin\msvc50engmatopts.bat filename.c
where filename i s the name of the source fi l e.
UNIX Fortran
SGI 64 f77 64 mips4 <include dir> o <result> <source> <libdir> <libraries>
DEC Al pha f77 fpe3 <include dir> o <result> <source> <libdir> <libraries>
Al l others f77 <include dir> o <result> <source> <libdir> <libraries>
where:
<include dir> i s I<matlab>/extern/include
<result> i s the name of the resul ti ng program
<source> i s the l i st of source fi l es
<libdir> i s L<matlab>/extern/lib/$ARCH
<libraries> i s lmat lmx
Table 5-8: Compiling and Linking MAT-File Programs (Continued)
5 Data Export and Import
5-32
6
Usi ng the MATLAB
Engi ne
Interprocess Communication: TheMATLAB Engine . . 6-2
The Engi ne Li brary . . . . . . . . . . . . . . . . . . 6-3
Communi cati ng wi th MATLAB . . . . . . . . . . . . . 6-4
Examples . . . . . . . . . . . . . . . . . . . . . 6-5
Cal l i ng the MATLAB Engi ne . . . . . . . . . . . . . . 6-5
Compilingand LinkingEnginePrograms . . . . . . . 6-14
Speci al Consi derati ons . . . . . . . . . . . . . . . . 6-14
UNI X . . . . . . . . . . . . . . . . . . . . . . . 6-16
Wi ndows . . . . . . . . . . . . . . . . . . . . . . 6-18
6 Using the MATLAB Engine
6-2
Interprocess Communication: The MATLAB Engine
The MATLAB engi ne l i brary i s a set of routi nes that al l ows you to cal l
MATLAB from your own programs, thereby empl oyi ng MATLAB as a
computati on engi ne. Some of the thi ngs you can do wi th the MATLAB engi ne
are:
Cal l a math routi ne, for exampl e, to i nvert an array or to compute an FFT
from your own program. When empl oyed i n thi s manner, MATLAB i s a
powerful and programmabl e mathemati cal subrouti ne l i brary.
Bui l d an enti re system for a speci fi c task, for exampl e, radar si gnature
anal ysi s or gas chromatography, where the front end (GUI ) i s programmed
i n C and the back end (anal ysi s) i s programmed i n MATLAB, thereby
shorteni ng devel opment ti me.
The MATLAB engi ne operates by runni ng i n the background as a separate
process from your own program. Thi s offers several advantages:
On UNI X, the MATLAB engi ne can run on your machi ne, or on any other
UNI X machi ne on your network, i ncl udi ng machi nes of a di fferent
archi tecture. Thus you coul d i mpl ement a user i nterface on your workstati on
and perform the computati ons on a faster machi ne l ocated el sewhere on your
network. See the engOpen reference page, whi ch i s accessi bl e from the
MATLAB Hel p Desk, for further i nformati on.
I nstead of requi ri ng that al l of MATLAB be l i nked to your program
(a substanti al amount of code), onl y a smal l engi ne communi cati on l i brary i s
needed.
Interprocess Communication: The MATLAB Engine
6-3
The Engine Library
The engi ne l i brary contai ns the fol l owi ng routi nes for control l i ng the MATLAB
computati on engi ne. Thei r names al l begi n wi th the three-l etter prefi x eng.
These tabl es l i st al l the avai l abl e engi ne functi ons and thei r purposes.
The MATLAB engi ne al so uses the mx prefi xed API routi nes di scussed i n the
Creati ng C Language MEX-Fi l es and Creati ng Fortran MEX-Fi l es chapters
of thi s book.
Table 6-1: C Engine Routines
Function Purpose
engOpen Start up MATLAB engi ne
engClose Shut down MATLAB engi ne
engGetArray Get a MATLAB array from the MATLAB engi ne
engPutArray Send a MATLAB array to the MATLAB engi ne
engEvalString Execute a MATLAB command
engOutputBuffer Create a buffer to store MATLAB text output
Table 6-2: Fortran Engine Routines
Function Purpose
engOpen Start up MATLAB engi ne
engClose Shut down MATLAB engi ne
engGetMatrix Get a MATLAB array from the MATLAB engi ne
engPutMatrix Send a MATLAB array to the MATLAB engi ne
engEvalString Execute a MATLAB command
engOutputBuffer Create a buffer to store MATLAB text output
6 Using the MATLAB Engine
6-4
Communicating with MATLAB
On UNI X, the engi ne l i brary communi cates wi th the MATLAB engi ne usi ng
pi pes, and, i f needed, rsh for remote executi on. On Mi crosoft Wi ndows, the
engi ne l i brary communi cates wi th MATLAB usi ng Acti veX. The next chapter,
Cl i ent/Server Appl i cati ons, contai ns a detai l ed descri pti on of Acti veX.
Note: On the PC, support for MATLAB 5 data types and sparse matri ces i s
not avai l abl e i n engi ne appl i cati ons.
Examples
6-5
Examples
Calling the MATLAB Engine
C Example
Thi s program, engdemo.c, i l l ustrates how to cal l the engi ne functi ons from a
stand-al one C program. For the Wi ndows versi on of thi s program, see
engwindemo.c i n the <matlab>\extern\examples\eng_mat di rectory. Engi ne
exampl es, l i ke the MAT-fi l e exampl es, are l ocated i n the eng_mat di rectory.
/* $Revision: 1.3 $ */
/*
* engdemo.c
*
* This is a simple program that illustrates how to call the
* MATLAB engine functions from a C program.
*
* Copyright (c) 1996-1998 The MathWorks, Inc.
* All rights reserved
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "engine.h"
#define BUFSIZE 256
int main()
{
Engine *ep;
mxArray *T = NULL, *result = NULL;
char buffer[BUFSIZE];
double time[10] = { 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0,
8.0, 9.0 };
6 Using the MATLAB Engine
6-6
/*
* Start the MATLAB engine locally by executing the string
* "matlab".
*
* To start the session on a remote host, use the name of
* the host as the string rather than \0
*
* For more complicated cases, use any string with whitespace,
* and that string will be executed literally to start MATLAB.
*/
if (!(ep = engOpen("\0"))) {
fprintf(stderr, "\nCan't start MATLAB engine\n");
return EXIT_FAILURE;
}
/*
* PART I
*
* For the first half of this demonstration, we will send data
* to MATLAB, analyze the data, and plot the result.
*/
/*
* Create a variable for our data.
*/
T = mxCreateDoubleMatrix(1, 10, mxREAL);
mxSetName(T, "T");
memcpy((void *)mxGetPr(T), (void *)time, sizeof(time));
/*
* Place the variable T into the MATLAB workspace.
*/
engPutArray(ep, T);
/*
* Evaluate a function of time, distance = (1/2)g.*t.^2
* (g is the acceleration due to gravity).
*/
engEvalString(ep, "D = .5.*(9.8).*T.^2;");
Examples
6-7
/*
* Plot the result.
*/
engEvalString(ep, "plot(T,D);");
engEvalString(ep, "title('Position vs. Time for a falling
object');");
engEvalString(ep, "xlabel('Time (seconds)');");
engEvalString(ep, "ylabel('Position (meters)');");
/*
* Use fgetc() to make sure that we pause long enough to be
* able to see the plot.
*/
printf("Hit return to continue\n\n");
fgetc(stdin);
/*
* We're done for Part I! Free memory, close MATLAB engine.
*/
printf("Done for Part I.\n");
mxDestroyArray(T);
engEvalString(ep, "close;");
/*
* PART II
*
* For the second half of this demonstration, we will request
* a MATLAB string, which should define a variable X. MATLAB
* will evaluate the string and create the variable. We
* will then recover the variable, and determine its type.
*/
/*
* Use engOutputBuffer to capture MATLAB output, so we can
* echo it back.
*/
engOutputBuffer(ep, buffer, BUFSIZE);
while (result == NULL) {
char str[BUFSIZE];
6 Using the MATLAB Engine
6-8
/*
* Get a string input from the user.
*/
printf("Enter a MATLAB command to evaluate. This
command should\n");
printf("create a variable X. This program will then
determine\n");
printf("what kind of variable you created.\n");
printf("For example: X = 1:5\n");
printf(">> ");
fgets(str, BUFSIZE1, stdin);
/*
* Evaluate input with engEvalString.
*/
engEvalString(ep, str);
/*
* Echo the output from the command. First two characters
* are always the double prompt (>>).
*/
printf("%s", buffer+2);
/*
* Get result of computation.
*/
printf("\nRetrieving X...\n");
if ((result = engGetArray(ep,"X")) == NULL)
printf("Oops! You didn't create a variable X.\n\n");
else {
printf("X is class %s\t\n", mxGetClassName(result));
}
}
Examples
6-9
/*
* We're done! Free memory, close MATLAB engine and exit.
*/
printf("Done!\n");
mxDestroyArray(result);
engClose(ep);
return EXIT_SUCCESS;
}
The fi rst part of thi s program l aunches MATLAB and sends i t data. MATLAB
then anal yzes the data and pl ots the resul ts.
The program then conti nues wi th
Hit return to continue
Pressi ng Return conti nues the program.
Done for Part I.
Enter a MATLAB command to evaluate. This command should
create a variable X. This program will then determine
what kind of variable you created.
For example: X = 1:5
6 Using the MATLAB Engine
6-10
Enteri ng X = 17.5 conti nues the program executi on.
X = 17.5
X =
17.5000
Retrieving X...
X is class double
Done!
Fi nal l y, the program frees memory, cl oses the MATLAB engi ne, and exi ts.
Fortran Example
Thi s program, fengdemo.f, i l l ustrates how to cal l the engi ne functi ons from a
stand-al one Fortran program.
C
C fengdemo.f
C
C This program illustrates how to call the
C MATLAB Engine functions from a Fortran program.
C
C Copyright (c) 1997-1998 The MathWorks, Inc.
C All rights reserved
C==============================================================
C $Revision: 1.2 $
program main
C--------------------------------------------------------------
C (integer) Replace integer by integer*8 on the DEC Alpha
C and the SGI 64 platforms.
C
integer engOpen, engGetMatrix, mxCreateFull, mxGetPr
integer ep, T, D, result
C--------------------------------------------------------------
Examples
6-11
C
C Other variable declarations here
double precision time(10), dist(10)
integer stat, temp
data time / 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0 /
C
ep = engOpen('matlab ')
C
if (ep .eq. 0) then
write(6,*) 'Can''t start MATLAB engine'
stop
endif
C
T = mxCreateFull(1, 10, 0)
call mxSetName(T, 'T')
call mxCopyReal8ToPtr(time, mxGetPr(T), 10)
C
C
C Place the variable T into the MATLAB workspace.
C
call engPutMatrix(ep, T)
C
C
C Evaluate a function of time, distance = (1/2)g.*t.^2
C (g is the acceleration due to gravity).
C
call engEvalString(ep, 'D = .5.*(9.8).*T.^2;')
C
C
C Plot the result.
C
call engEvalString(ep, 'plot(T,D);')
call engEvalString(ep, 'title(''Position vs. Time'')')
call engEvalString(ep, 'xlabel(''Time (seconds)'')')
call engEvalString(ep, 'ylabel(''Position (meters)'')')
C
6 Using the MATLAB Engine
6-12
C
C Read from console to make sure that we pause long enough to be
C 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
C
call engEvalString(ep, 'close;')
C
D = engGetMatrix(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
C
C
call mxFreeMatrix(T)
call mxFreeMatrix(result)
stat = engClose(ep)
C
stop
end
Examples
6-13
Executi ng thi s program l aunches MATLAB, sends i t data, and pl ots the
resul ts.
The program conti nues wi th
Type 0 <return> to Exit
Type 1 <return> to continue
Enteri ng 1 at the prompt conti nues the program executi on.
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.
Fi nal l y, the program frees memory, cl oses the MATLAB engi ne, and exi ts.
6 Using the MATLAB Engine
6-14
Compiling and Linking Engine Programs
To produce an executabl e versi on of an engi ne program, you must compi l e i t
and l i nk i t wi th the appropri ate l i brary. Thi s secti on descri bes the steps
requi red to compi l e and l i nk engi ne programs on UNI X and Wi ndows systems.
I t begi ns by l ooki ng at a speci al consi derati on for compi l ers that do not mask
fl oati ng-poi nt excepti ons.
Special Considerations
Floating-Point Exceptions
Certai n mathemati cal operati ons can resul t i n nonfi ni te val ues. For exampl e,
di vi si on by zero resul ts i n the nonfi ni te I EEE val ue, inf. A fl oati ng-poi nt
excepti on occurs when such an operati on i s performed. Because MATLAB uses
an I EEE model that supports nonfi ni te val ues such as inf and NaN, MATLAB
di sabl es, or masks, fl oati ng-poi nt excepti ons.
Some compi l ers do not mask fl oati ng-poi nt excepti ons by defaul t. Thi s causes
engi ne programs bui l t wi th such compi l ers to termi nate when a fl oati ng-poi nt
excepti on occurs. Consequentl y, you need to take speci al precauti ons when
usi ng these compi l ers to mask fl oati ng-poi nt excepti ons so that your engi ne
appl i cati on wi l l perform properl y.
Note: MATLAB-based appl i cati ons shoul d never get fl oati ng-poi nt
excepti ons. I f you do get a fl oati ng-poi nt excepti on, veri fy that any thi rd party
l i brari es that you l i nk agai nst do not enabl e fl oati ng-poi nt excepti on handl i ng.
Thi s tabl e shows the pl atforms and compi l ers on whi ch you shoul d mask
fl oati ng-poi nt excepti ons.
Platform Compiler
DEC Al pha DI GI TAL Fortran 77
Li nux Absoft Fortran
Wi ndows Borl and C++
Compiling and Linking Engine Programs
6-15
DEC Alpha. To mask fl oati ng-poi nt excepti ons on the DEC Al pha pl atform, use
the fpe3 compi l e fl ag. For exampl e,
f77 fpe3
Absoft Fortran Compiler on Linux. To mask fl oati ng-poi nt excepti ons when usi ng
the Absoft Fortran compi l er on the Li nux pl atform, you must add some code to
your program. I ncl ude the fol l owi ng at the begi nni ng of your main() program,
before any cal l s to MATLAB API functi ons.
integer cw, arm387
C
cw = arm387(z'0000003F')
cw = cw .or. z'0000003F'
call arm387(cw)
Borland C++ Compiler on Windows. To mask fl oati ng-poi nt excepti ons when usi ng
the Borl and C++ compi l er on the Wi ndows pl atform, you must add some code
to your program. I ncl ude the fol l owi ng at the begi nni ng of your main() or
WinMain() functi on, before any cal l s to MATLAB API functi ons.
#include <float.h>
.
.
.
_control87(MCW_EM,MCW_EM);
.
.
.
6 Using the MATLAB Engine
6-16
UNIX
Under UNI X at runti me, you must tel l the system where the API shared
l i brari es resi de. These secti ons provi de the necessary UNI X commands
dependi ng on your shel l and system archi tecture.
Setting Runtime Library Path
I n C shel l , the command to set the l i brary path i s
setenv LD_LIBRARY_PATH <matlab>/extern/lib/$Arch:$LD_LIBRARY_PATH
I n Bourne shel l , the commands to set the l i brary path are
LD_LIBRARY_PATH=<matlab>/extern/lib/$Arch:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH
where:
<matlab> i s the MATLAB root di rectory and $Arch i s your system archi tecture
(alpha, lnx86, sgi, sol2, sun4, hp700, ibm_rs, or sgi64). Note that the
envi ronment vari abl e (LD_LIBRARY_PATH i n thi s exampl e) vari es on several
pl atforms. Tabl e 6-3 l i sts the di fferent envi ronment vari abl e names you shoul d
use on these systems.
I t i s conveni ent to pl ace these commands i n a startup scri pt such as ~/.cshrc
for C shel l or ~/.profile for Bourne shel l .
Compiling and Linking Commands
Tabl e 6-4 pr ovi des the commands requi r ed to compi l e and l i nk engi ne C and
Fortran programs on UNI X pl atforms.
Table 6-3: Environment Variables Name
Architecture Environment Variable
HP700 SHLIB_PATH
I BM RS/6000 LIBPATH
SGI 64 LD_LIBRARY64_PATH
Compiling and Linking Engine Programs
6-17
You can now run the executabl e you have just produced.
Special Consideration for Fortran (f77) on HP-UX 10.x
I n the versi on of the Fortran compi l er (f77) that shi ps wi th HP-UX 10.x, the
meani ng of the L fl ag has changed. The L fl ag now requests a l i sti ng. So, to
force the l i nker to see the l i brari es you want l i nked i n wi th your code, use
f77 <include dir> o <result> <source> Wl,L<matlab>/extern/lib/hp700 <libraries>
Table 6-4: Compiling and Linking Engine Programs
UNIX C Command
HP700 cc Aa <include dir> o <result> <source> <libdir> <libraries>
SGI 64 cc 64 mips4 <include dir> o <result> <source> <libdir> <libraries>
Li nux gcc ansi <include dir> o <result> <source> <libdir> <libraries>
SunOS 4.x acc <include dir> o <result> <source> <libdir> <libraries>
Al l others cc <include dir> o <result> <source> <libdir> <libraries>
UNIX Fortran
SGI 64 f77 64 mips4 <include dir> o <result> <source> <libdir> <libraries>
DEC Al pha f77 fpe3 <include dir> o <result> <source> <libdir> <libraries>
Al l others f77 <include dir> o <result> <source> <libdir> <libraries>
where:
<include dir> i s I<matlab>/extern/include
<result> i s the name of the resul ti ng program
<source> i s the l i st of source fi l es
<libdir> i s L<matlab>/extern/lib/$ARCH
<libraries> i s leng lmx
6 Using the MATLAB Engine
6-18
Windows
To compi l e and l i nk engi ne programs, use the mex scri pt wi th an engi ne opti ons
fi l e. watengmatopts.bat, wat11engmatopts.bat, bccengmatopts.bat,
df50engmatopts.bat, msvc50engmatopts.bat, and msvcengmatopts.bat are
stand-al one engi ne and MAT opti ons fi l es (l ocated i n <matlab>\bin). For
exampl e, to compi l e and l i nk a stand-al one engi ne appl i cati on on Wi ndows
usi ng MSVC (Versi on 5.0) use
mex f <matlab>\bin\msvc50engmatopts.bat filename.c
where filename i s the name of the source fi l e.
7
Cl i ent/Server Appl i cati ons
MATLAB ActiveX Integration . . . . . . . . . . . . 7-2
What I s Acti veX? . . . . . . . . . . . . . . . . . . . 7-2
MATLAB Acti veX Cl i ent Support . . . . . . . . . . . . 7-4
Addi ti onal Acti veX Cl i ent I nformati on . . . . . . . . . . 7-23
MATLAB Acti veX Automati on Server Support . . . . . . . 7-26
Addi ti onal Acti veX Server I nformati on . . . . . . . . . . 7-30
Dynamic Data Exchange(DDE) . . . . . . . . . . . 7-32
DDE Concepts and Termi nol ogy . . . . . . . . . . . . 7-32
Accessi ng MATLAB As a Server . . . . . . . . . . . . 7-34
Usi ng MATLAB As a Cl i ent . . . . . . . . . . . . . . 7-39
DDE Advi sory Li nks . . . . . . . . . . . . . . . . . 7-41
7 Client/Server Applications
7-2
MATLAB ActiveX Integration
What Is ActiveX?
Acti veX i s a Mi crosoft Wi ndows protocol for component i ntegrati on. Usi ng
Acti veX, devel opers and end users can sel ect appl i cati on-speci fi c, Acti veX
components produced by di fferent vendors and seaml essl y i ntegrate them i nto
a compl ete appl i cati on sol uti on. For exampl e, a si ngl e appl i cati on may requi re
database access, mathemati cal anal ysi s, and presentati on qual i ty busi ness
graphs. Usi ng Acti veX, a devel oper may choose a database access component
by one vendor, a busi ness graph component by another, and i ntegrate these
i nto a mathemati cal anal ysi s package produced by yet a thi rd.
ActiveX Concepts and Terminology
COM. Acti veX i s a fami l y of rel ated object-ori ented technol ogi es that have a
common root, cal l ed the Component Object Model, or COM. Each
object-ori ented l anguage or envi ronment has an object model that defi nes
certai n characteri sti cs of objects i n that envi ronment, such as how objects are
l ocated, i nstanti ated, or i denti fi ed. COM defi nes the object model for al l
Acti veX objects.
ActiveX Interfaces. Each Acti veX object supports one or more named i nterfaces.
An interfacei s a l ogi cal l y rel ated col l ecti on of methods, properti es, and events.
Methods are si mi l ar to functi on cal l s i n that they are a request for the object to
perform some acti on. Properti es are state vari abl es mai ntai ned by the object,
such as the col or of text, or the name of a fi l e on whi ch the control i s acti ng.
Events are noti fi cati ons that the control forwards back to i ts cl i ent (si mi l ar to
Handl e Graphi cs