You are on page 1of 259

Computation

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

i s a compl ete, sel f-contai ned envi ronment for


programmi ng and mani pul ati ng data, i t i s often useful to i nteract wi th data
and programs external to the MATLAB envi ronment. MATLAB provi des an
Appl i cati on Program I nterface (API ) to support these external i nterfaces. The
functi ons supported by the API i ncl ude:
Cal l i ng C or Fortran programs from MATLAB.
I mporti ng and exporti ng data to and from the MATLAB envi ronment.
Establ i shi ng cl i ent/server rel ati onshi ps between MATLAB and other
software programs.
MEX-Files
You can cal l your own C or Fortran subrouti nes from MATLAB as i f they were
bui l t-i n functi ons. MATLAB cal l abl e C and Fortran programs are referred to
as MEX-fi l es. MEX-fi l es are dynami cal l y l i nked subrouti nes that the MATLAB
i nterpreter can automati cal l y l oad and execute.
MEX-fi l es have several appl i cati ons:
Large pre-exi sti ng C and Fortran programs can be cal l ed from MATLAB
wi thout havi ng to be rewri tten as M-fi l es.
Bottl eneck computati ons (usual l y for-l oops) that do not run fast enough i n
MATLAB can be recoded i n C or Fortran for effi ci ency.
Thi s book uses many exampl es to show how to wri te C and Fortran MEX-fi l es.
MAT-File Applications
You can use MAT-fi l es, the data fi l e format MATLAB uses for savi ng data to
di sk, to i mport data to and export data from the MATLAB envi ronment.
MAT-fi l es provi de a conveni ent mechani sm for movi ng your MATLAB data
between di fferent pl atforms i n a hi ghl y portabl e manner. I n addi ti on, they
provi de a means to i mport and export 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 provi de a l i brary of access routi nes 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 API routi nes di scussed i n thi s book.
Introduction to MATLAB API
1-3
Engine Applications
MATLAB provi des 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.
MATLAB engi ne programs are C or Fortran programs that communi cate wi th
a separate MATLAB process vi a pi pes (i n UNI X) and through Acti veX on
Wi ndows. There i s a l i brary of functi ons provi ded wi th MATLAB that al l ows
you to start and end the MATLAB process, send data to and from MATLAB,
and send commands to be processed i n MATLAB.
Some of the thi ngs you can do wi th the MATLAB engi ne are:
Cal l a math routi ne to i nvert an array or to compute an FFTfrom 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.
1 Introducing the MATLAB API
1-4
MATLAB Data
The MATLAB Array
Before you can program MEX-fi l es, you must understand how MATLAB
represents the many data types i t supports. The MATLAB l anguage works
wi th onl y a si ngl e object type: the MATLAB array. Al l MATLAB vari abl es,
i ncl udi ng scal ars, vectors, matri ces, stri ngs, cel l arrays, structures, and objects
are stored as MATLAB arrays. I n C, the MATLAB array i s decl ared to be of
type mxArray. The mxArray structure contai ns, among other thi ngs:
I ts type
I ts di mensi ons
The data associ ated wi th thi s array
I f numeri c, whether the vari abl e i s real or compl ex
I f sparse, i ts i ndi ces and nonzero maxi mum el ements
I f a structure or object, the number of fi el ds and fi el d names
Data Storage
Al l MATLAB data i s stored col umnwi se. Thi s i s how Fortran stores matri ces;
MATLAB uses thi s conventi on because i t was ori gi nal l y wri tten i n Fortran. For
exampl e, gi ven the matri x
a=['house'; 'floor'; 'porch']
a =
house
floor
porch
i ts di mensi ons are
size(a)
ans =
3 5
MATLAB Data
1-5
and i ts data i s stored as
Data Types in MATLAB
Complex Double-Precision Matrices
The most common data type i n MATLAB i s the compl ex doubl e-preci si on,
nonsparse matri x. These matri ces are of type double and have di mensi ons
m-by-n, where m i s the number of rows and n i s the number of col umns. The data
i s stored as two vectors of doubl e-preci si on numbers one contai ns the real
data and one contai ns the i magi nary data. The poi nters to thi s data are
referred to as pr (poi nter to real data) and pi (poi nter to i magi nary data),
respecti vel y. A real -onl y, doubl e-preci si on matri x i s one whose pi i s NULL.
Numeric Matrices
MATLAB al so supports other types of numeri c matri ces. These are
si ngl e-preci si on fl oati ng-poi nt and 8-, 16-, and 32-bi t i ntegers, both si gned and
unsi gned. The data i s stored i n two vectors i n the same manner as
doubl e-preci si on matri ces.
MATLAB Strings
MATLAB stri ngs are of type char and are stored the same way as unsi gned
16-bi t i ntegers except there i s no i magi nary data component. Each character i n
the stri ng i s stored as 16-bi t ASCI I Uni code. Unl i ke C, MATLAB stri ngs are
not nul l termi nated.
Sparse Matrices
Sparse matri ces have a di fferent storage conventi on i n MATLAB. The
parameters pr and pi are sti l l arrays of doubl e-preci si on numbers, but there
are three addi ti onal parameters, nzmax, ir, and jc:
nzmax i s an i nteger that contai ns the l ength of ir, pr, and, i f i t exi sts, pi. I t
i s the maxi mum possi bl e number of nonzero el ements i n the sparse matri x.
ir poi nts to an i nteger array of l ength nzmax contai ni ng the row i ndi ces of the
correspondi ng el ements i n pr and pi.
h f p o l o u o r s o c e r h
1 Introducing the MATLAB API
1-6
jc poi nts to an i nteger array of l ength N+1 that contai ns col umn i ndex
i nformati on. For j, i n the range 0 j N1, jc[j] i s the i ndex i n ir and pr
(and pi i f i t exi sts) of the fi rst nonzero entry i n the jth col umn and
jc[j+1] 1 i ndex of the l ast nonzero entry. As a resul t, jc[N] i s al so equal
to nnz, the number of nonzero entri es i n the matri x. I f nnz i s l ess than nzmax,
then more nonzero entri es can be i nserted i n the array wi thout al l ocati ng
addi ti onal storage.
Cell Arrays
Cel l arrays are a col l ecti on of MATLAB arrays where each mxArray i s referred
to as a cel l . Thi s al l ows MATLAB arrays of di fferent types to be stored together.
Cel l arrays are stored i n a si mi l ar manner to numeri c matri ces, except the data
porti on contai ns a si ngl e vector of poi nters to mxArrays. Members of thi s vector
are cal l ed cel l s. Each cel l can be of any supported data type, even another cel l
array.
Structures
A 1-by-1 structure i s stored i n the same manner as a 1-by-n cel l array where n
i s the number of fi el ds i n the structure. Members of the data vector are cal l ed
fi el ds. Each fi el d i s associ ated wi th a name stored i n the mxArray.
Objects
Objects are stored and accessed the same way as structures. I n MATLAB,
objects are named structures wi th regi stered methods. Outsi de MATLAB, an
object i s a structure that contai ns storage for an addi ti onal cl assname that
i denti fi es the name of the object.
Multidimensional Arrays
MATLAB arrays of any type can be mul ti di mensi onal . A vector of i ntegers i s
stored where each el ement i s the si ze of the correspondi ng di mensi on. The
storage of the data i s the same as matri ces.
Logical Arrays
Any noncompl ex numeri c or sparse array can be fl agged as l ogi cal . The storage
for a l ogi cal array i s the same as the storage for a nonl ogi cal array.
MATLAB Data
1-7
Empty Arrays
MATLAB arrays of any type can be empty. An empty mxArray i s one wi th at
l east one di mensi on equal to zero. For exampl e, a doubl e-preci si on mxArray of
type double, where m and n equal 0 and pr i s NULL, i s an empty array.
Using Data Types
The si x fundamental data types i n MATLAB are double, char, sparse, uint8,
cell, and struct. You can wri te MEX-fi l es, MAT-fi l e appl i cati ons, and engi ne
appl i cati ons i n C that accept any data type supported by MATLAB. I n Fortran,
onl y the creati on of doubl e-preci si on n-by-m arrays and stri ngs are supported.
You can treat C and Fortran MEX-fi l es, once compi l ed, exactl y l i ke
M-functi ons.
The explore Example
There i s an exampl e MEX-fi l e i ncl uded wi th MATLAB, cal l ed explore, that
i denti fi es the data type of an i nput vari abl e. For exampl e, typi ng
cd([matlabroot '/extern/examples/mex']);
x = 2;
explore(x);
produces thi s resul t
------------------------------------------------
Name: x
Dimensions: 1x1
Class Name: double
------------------------------------------------
(1,1) = 2
explore accepts any data type. Try usi ng explore wi th these exampl es:
explore([1 2 3 4 5])
explore 1 2 3 4 5
explore({1 2 3 4 5})
explore(int8([1 2 3 4 5]))
explore {1 2 3 4 5}
explore(sparse(eye(5)))
explore(struct('name', 'Joe Jones', 'ext', 7332))
explore(1, 2, 3, 4, 5)
1 Introducing the MATLAB API
1-8
API Documentation
The API Documentation Set
Thi s book, the Application ProgramI nterfaceGuide, contai ns confi gurati on
i nformati on and tutori al s for usi ng the MATLAB API . The compl ete set of
reference documentati on for al l the API -rel ated functi ons i s provi ded onl i ne,
and can be accessed from the MATLAB Hel p Desk by typi ng helpdesk at the
MATLAB prompt. From the Hel p Desk, you can al so access onl i ne (PDF)
versi ons of the Application ProgramI nterfaceGuideand the Application
ProgramI nterfaceReference. The onl i ne versi on of the Application Program
I nterfaceReferencei s the compl ete set of API reference pages i n a book format.
I f you need a pri nted versi on of the API reference pages, you can easi l y pri nt
the PDF versi on of the Application ProgramI nterfaceReference.
API Tutorial Files
I n addi ti on to the pri nted Application ProgramI nterfaceGuideand the onl i ne
Application ProgramI nterfaceReferencethat i s accessi bl e vi a the Hel p Desk,
there are many sampl e fi l es i ncl uded wi th MATLAB that can hel p you l earn
how to use the API . The mex and mx subdi rectori es i n the extern/examples
di rectory contai n exampl es that are referenced from the mex and mx functi ons
i n the onl i ne Application ProgramI nterfaceReference.
The refbook subdi rectory i n the extern/examples di rectory contai ns the
MEX-fi l e exampl es (C and Fortran) that are used i n thi s book, the Application
ProgramI nterfaceGuide. The eng_mat subdi rectory i n the extern/examples
di rectory contai ns exampl es that are referenced from the engi ne and MAT-fi l e
routi nes i n the onl i ne Application ProgramI nterfaceReferenceand the engi ne
(Chapter 6) and MAT-fi l e (Chapter 5) chapters i n thi s book.
API Documentation
1-9
Note: You can fi nd the most recent versi ons of the exampl e programs from
thi s book at the anonymous FTP server:
ftp.mathworks.com/pub/tech-support/library/matlab5/extern/examples/
refbook
You can fi nd the most recent versi ons of the exampl es descri bed i n the onl i ne
Application ProgramI nterfaceReferenceat:
ftp.mathworks.com/pub/tech-support/library/matlab5/extern/examples/mex
ftp.mathworks.com/pub/tech-support/library/matlab5/extern/examples/mx
ftp.mathworks.com/pub/tech-support/library/matlab5/extern/examples/
eng_mat
How This Book Is Organized
Chapter 1 provi des an overvi ew of MEX-fi l es, MAT-fi l e appl i cati ons, engi ne
appl i cati ons, and the way MATLAB stores i ts data. Thi s chapter al so descri bes
the API documentati on set.
Chapter 2 di scusses MEX-fi l es, whi ch enabl e you to cal l your own C or Fortran
subrouti nes di rectl y from MATLAB. I t al so provi des basi c i nformati on to get
you up and runni ng so that you can confi gure your system to bui l d
MEX-functi ons.
Chapters 3 and 4 contai n C and Fortran exampl es, whi ch expl ai n how to create
MEX-fi l es on di fferent pl atforms.
Chapter 5 conti nues wi th a di scussi on of techni ques for i mporti ng and
exporti ng data to and from the MATLAB envi ronment. The most i mportant
techni que i s MAT-fi l es the fi l es MATLAB uses for savi ng data to a di sk.
MAT-fi l es offer a si mpl e and conveni ent mechani sm for transporti ng your data
between di fferent pl atforms. They al so enabl e you to i mport and export your
MATLAB data to and from other MATLAB stand-al one appl i cati ons. To
si mpl i fy the use of MAT-fi l es wi th other appl i cati ons, a l i brary of access
routi nes i s provi ded, whi ch makes i t very easy to read and wri te MAT-fi l es
usi ng your own C or Fortran programs.
1 Introducing the MATLAB API
1-10
Chapter 6 di scusses the MATLAB engi ne, whi ch enabl es you to set up cl i ent/
server rel ati onshi ps between MATLAB and other software programs, such as
Excel .
Chapter 7 i ncl udes i nformati on on Acti veX, whi ch i s a component i ntegrati on
technol ogy for Mi crosoft Wi ndows. Thi s chapter al so contai ns i nformati on on
dynami c data exchange (DDE) software that al l ows Mi crosoft Wi ndows
appl i cati ons to communi cate wi th each other by exchangi ng data.
Chapter 8 focuses on pl atform-speci fi c i ssues and provi des detai l ed
i nformati on on the mex scri pt. I n addi ti on, Chapter 8 contai ns i nformati on on
troubl eshooti ng and memory management.
The Appendi ces contai n suppl emental i nformati on regardi ng the MATLAB
API . Appendi x A l i sts the set of API functi ons i ncl udi ng C and Fortran
MX-functi ons, C and Fortran MEX-functi ons, C and Fortran MAT-fi l e
routi nes, C and Fortran engi ne routi nes, and DDE routi nes. Appendi x B
descri bes the di rectory organi zati on and purpose of the fi l es associ ated wi th
the MATLAB API .
2
Getti ng Started
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
BuildingMEX-Files . . . . . . . . . . . . . . . . . 2-4
Testi ng Your Confi gurati on . . . . . . . . . . . . . . 2-4
Usi ng f to Speci fy an Opti ons Fi l e . . . . . . . . . . . 2-8
TroubleshootingYour Configuration . . . . . . . . . 2-12
2 Getting Started
2-2
Introducing MEX-Files
MEX-fi l es are dynami cal l y l i nked subrouti nes that the MATLAB i nterpreter
can automati cal l y l oad and execute. MEX-fi l es are not appropri ate for al l
appl i cati ons. MATLAB i s a hi gh-producti vi ty system whose speci al ty i s
el i mi nati ng ti me-consumi ng, l ow-l evel programmi ng i n compi l ed l anguages
l i ke Fortran or C. I n general , most programmi ng shoul d be done i n MATLAB.
Dont use the MEX faci l i ty unl ess your appl i cati on requi res i t.
Using MEX-Files
MEX-fi l es are subrouti nes produced from C or Fortran source code. They
behave just l i ke M-fi l es and bui l t-i n functi ons. Whi l e M-fi l es have a
pl atform-i ndependent extensi on, .m, MATLAB i denti fi es MEX-fi l es by
pl atform-speci fi c extensi ons. Tabl e 2-1 l i sts the pl atform-speci fi c extensi ons for
MEX-fi l es.
You can cal l MEX-fi l es exactl y as you woul d cal l any M-functi on. For exampl e,
a MEX-fi l e cal l ed conv2.mex on your di sk i n the MATLAB datafun tool box
di rectory performs a 2-D convol uti on of matri ces. conv2.m onl y contai ns the
hel p text documentati on. I f you i nvoke the functi on conv2 from i nsi de
Table 2-1: MEX-File Extensions
Platform MEX-File Extension
Sun OS 4.x mex4
HP 9000/seri es 700 mexhp7
Al pha mexaxp
SGI mexsg
SGI 64 mexsg64
I BM RS/6000 mexrs6
Li nux mexlx
Sol ari s mexsol
Wi ndows dll
Introducing MEX-Files
2-3
MATLAB, the i nterpreter l ooks through the l i st of di rectori es on MATLABs
search path. I t scans each di rectory l ooki ng for the fi rst occurrence of a fi l e
named conv2 wi th the correspondi ng fi l ename extensi on from the tabl e or .m.
When i t fi nds one, i t l oads the fi l e and executes i t. MEX-fi l es take precedence
over M-fi l es when l i ke-named fi l es exi st i n the same di rectory. However, hel p
text documentati on i s sti l l read from the .m fi l e.
The Distinction Between mx and mex Prefixes
Routi nes i n the API that are prefi xed wi th mx al l ow you to create, access,
mani pul ate, and destroy mxArrays. Routi nes prefi xed wi th mex perform
operati ons back i n the MATLAB envi ronment.
mx Routines
The array access and creati on l i brary provi des a set of array access and
creati on routi nes for mani pul ati ng MATLAB arrays. These subrouti nes, whi ch
are ful l y documented i n the onl i ne API reference pages, al ways start wi th the
prefi x mx. For exampl e, mxGetPi retri eves the poi nter to the i magi nary data
i nsi de the array.
Al though most of the routi nes i n the array access and creati on l i brary l et you
mani pul ate the MATLAB array, there are two excepti ons the I EEE routi nes
and memory management routi nes. For exampl e, mxGetNaN returns a double,
not an mxArray.
mex Routines
Routi nes that begi n wi th the mex prefi x perform operati ons back i n the
MATLAB envi ronment. For exampl e, the mexEvalString routi ne eval uates a
stri ng i n the MATLAB workspace.
Note: mex routi nes are onl y avai l abl e i n MEX-functi ons.
2 Getting Started
2-4
Building MEX-Files
Your i nstal l ed versi on of MATLAB contai ns al l the tool s you need to work wi th
the API , except a C or Fortran compi l er. Dependi ng on your requi rements,
youl l need ei ther an ANSI C compi l er or a Fortran compi l er. Al so, i f you are
worki ng on a Mi crosoft Wi ndows pl atform, your compi l er must be abl e to create
32-bi t wi ndows dynami cal l y l i nked l i brari es (DLLs).
The API supports many compi l ers and provi des opti ons fi l es desi gned
speci fi cal l y for these compi l ers. Chapter 8, System Setup, provi des detai l ed
i nformati on on the compi l ers, opti ons fi l es, and customi zati on. There i s al so
addi ti onal i nformati on regardi ng opti ons fi l es l ater i n thi s chapter i n
Usi ng f to Speci fy an Opti ons Fi l e.
Dependi ng on your pl atform, you may have to do some prel i mi nary work before
you can create MEX-fi l es wi th the mex scri pt. The next secti on, Testi ng Your
Confi gurati on, takes you through the process of creati ng a MEX-fi l e on each
pl atform.
Note: The MathWorks pr ovi des an opti on (setup) for the mex scri pt that l ets
you easi l y choose or swi tch your compi l er on Wi ndows systems.
More detai l ed i nformati on about the mex scri pt i s provi ded i n Custom Bui l di ng
MEX-Fi l es i n Chapter 8. I n addi ti on, Chapter 8 contai ns a Troubl eshooti ng
secti on i f you are havi ng di ffi cul ti es creati ng MEX-fi l es.
Testing Your Configuration
The qui ckest way to check i f your system i s set up properl y to create MEX-fi l es
i s by tryi ng the actual process. There i s C source code for an exampl e,
yprime.c, and i ts Fortran counterpart, yprimef.f and yprimefg.f (Wi ndows)
and yprimef.F and yprimefg.F (UNI X), i ncl uded i n the
Building MEX-Files
2-5
<matlab>/extern/examples/mex di rectory, where <matlab> represents the
top-l evel di rectory where MATLAB i s i nstal l ed on your system.
Note: I n pl atform i ndependent di scussi ons that refer to di rectory paths, thi s
book uses the UNI X conventi on. For exampl e, a general reference to the mex
di rectory i s <matlab>/extern/examples/mex.
The fol l owi ng secti ons contai n confi gurati on i nformati on for creati ng
MEX-fi l es on UNI X and Wi ndows systems. I f, after fol l owi ng the i nstructi ons,
you have di ffi cul ty creati ng MEX-fi l es, refer to Chapter 8 for addi ti onal
troubl eshooti ng i nformati on.
On UNIX
To compi l e and l i nk the exampl e source fi l es, yprime.c or yprimef.F and
yprimefg.F, on UNI X, you must fi rst copy the fi l e(s) to a l ocal di rectory, and
then change di rectory (cd) to that l ocal di rectory.
At the MATLAB prompt, type
mex yprime.c
Thi s shoul d create the MEX-fi l e cal l ed yprime wi th the appropri ate extensi on
for your system.
You can now cal l yprime as i f i t were an M-functi on.
yprime(1,1:4)
ans =
2.0000 8.9685 4.0000 1.0947
To try the Fortran versi on of the sampl e program wi th your Fortran compi l er,
at the MATLAB prompt, type
mex yprimef.F yprimefg.F
I n addi ti on to runni ng the mex scri pt from the MATLAB prompt, you can al so
run the scri pt from the system prompt.
2 Getting Started
2-6
On Windows
Configuring an Options File. Before you can create MEX-fi l es on the Wi ndows
pl atform, you must confi gure the defaul t opti ons fi l e, mexopts.bat, for your
compi l er. The swi tch, setup, provi des an easy way for you to confi gure the
defaul t opti ons fi l e. You can run the setup opti on fr om ei ther the MATLAB or
DOS command prompt, and i t can be cal l ed anyti me to confi gure or change the
opti ons fi l e.
Executi ng the setup opti on presents a l i st of compi l ers whose opti ons fi l es are
currentl y shi pped i n the bin subdi rectory of MATLAB. Thi s exampl e shows
how to sel ect the Mi crosoft Vi sual C++ compi l er.
mex setup
Welcome to the utility for setting up compilers
for building external interface files.
Choose your C/C++ compiler:
[1] Borland C/C++ (version 5.0)
[2] Microsoft Visual C++ (version 4.2 or version 5.0)
[3] Watcom C/C++ (version 10.6 or version 11)
Fortran compilers
[4] DIGITAL Visual Fortran (version 5.0)
[0] None
compiler: 2
I f the sel ected compi l er has more than one opti ons fi l e (due to more than one
versi on of the compi l er), you are asked for a speci fi c versi on. For exampl e,
Choose the version of your C/C++ compiler:
[1] Microsoft Visual C++ 4.2
[2] Microsoft Visual C++ 5.0
version: 1
Building MEX-Files
2-7
You ar e then asked to enter the root di r ector y of your compi l er i nstal l ati on.
Please enter the location of your C/C++ compiler: [c:\msdev]
Note: Some compi l ers create a di rectory tree under thei r root di rectory when
you i nstal l them. You must respond to thi s prompt wi th the root di rectory onl y.
For exampl e, i f the compi l er creates di rectori es bin, lib, and include under
c:\msdev, you shoul d enter onl y the root di rectory, whi ch i s c:\msdev.
Fi nal l y, you are asked to veri fy your choi ces.
Please verify your choices:
Compiler: Microsoft Visual C++ 4.2
Location: c:\msdev
Are these correct?([y]/n): y
Default options file is being updated...
Building a MEX-File. To compi l e and l i nk the exampl e source fi l e on Wi ndows, at
the MATLAB prompt, type
cd([matlabroot '\extern\examples\mex'])
mex yprime.c
Thi s shoul d create the MEX-fi l e cal l ed yprime wi th the .DLL extensi on, whi ch
corresponds to the Wi ndows pl atform.
You can now cal l yprime as i f i t were an M-functi on.
yprime(1,1:4)
ans =
2.0000 8.9685 4.0000 1.0947
To try the Fortran versi on of the sampl e program wi th your Fortran compi l er
(mex setup al l ows you to change compi l ers anyti me), at the MATLAB prompt,
type
cd([matlabroot '\extern\examples\mex'])
mex yprimef.f yprimefg.f
2 Getting Started
2-8
I n addi ti on to runni ng the mex scri pt from the MATLAB prompt, you can al so
run the scri pt from the system prompt.
Using f to Specify an Options File
Wi ndows users can use the setup opti on to speci fy an opti ons fi l e. I n addi ti on,
al l users (UNI X and Wi ndows) can use the f opti on to speci fy an opti ons fi l e.
To use the f opti on, at the MATLAB prompt type
mex filename f <optionsfile>
and speci fy the name of the opti ons fi l e. Tabl e 2-2 contai ns a l i st of the opti ons
fi l es i ncl uded wi th MATLAB.
There are several si tuati ons when i t may be necessary to speci fy an opti ons fi l e
every ti me you use the mex scri pt. These i ncl ude:
(Windows) You want to use a di fferent compi l er (and not use the setup
opti on), or you want to compi l e MAT or engi ne stand-al one programs.
(UNI X) You do not want to use the system C compi l er.
Building MEX-Files
2-9
Preconfigured Options Files
MATLAB i ncl udes some preconfi gured opti ons fi l es that you can use wi th
parti cul ar compi l ers. Tabl e 2-2 l i sts the compi l ers whose opti ons fi l es are
i ncl uded wi th thi s rel ease of MATLAB.
Table 2-2: Options Files
Platform Compiler Options File
Wi ndows Mi crosoft C/C++, Versi on 4.2
Mi crosoft C/C++, Versi on 5.0
msvcopts.bat
msvc50opts.bat
DI GI TAL Vi sual Fortran,
Versi on 5.0
df50opts.bat
Watcom C/C++, Versi on 10.6
Watcom C/C++, Versi on 11
watcopts.bat
wat11copts.bat
Borl and C++, Versi on 5.0 bccopts.bat
Watcom C for Engi ne and MAT
stand-al one programs,
Versi on 10.6
Watcom C for Engi ne and MAT
stand-al one programs,
Versi on 11
watengmatopts.bat
wat11engmatopts.bat
Mi crosoft Vi sual C for Engi ne and
MAT stand-al one programs,
Versi on 4.2
Mi crosoft Vi sual C for Engi ne and
MAT stand-al one programs,
Versi on 5.0
msvcengmatopts.bat
msvc50engmatopts.bat
Borl and C for Engi ne and MAT
stand-al one programs,
Versi on 5.0
bccengmatopts.bat
DI GI TAL Vi sual Fortran for
MAT stand-al one programs,
Versi on 5.0
df50engmatopts.bat
2 Getting Started
2-10
Note: An up-to-date l i st of opti ons fi l es i s avai l abl e from our FTP server:
ftp.mathworks.com/pub/tech-support/library/matlab5/bin
For a l i st of al l the compi l ers supported by MATLAB, see the MathWorks
Techni cal Support Departments Techni cal Notes at
http://www.mathworks.com/support/tech-notes/#mex
Tabl e 2-3 shows where the defaul t opti ons fi l es are l ocated on each pl atform.
I f you want to use one of these opti ons fi l es,
1 Copy the desi red opti ons fi l e to the di rectory where you are creati ng your
MEX-fi l es. Opti ons fi l es are not M-fi l es, so they do not automati cal l y appear
i n the MATLAB path.
2 Speci fy the f <optionsfile> swi tch i n the mex command usi ng the
fi l ename of the desi red opti ons fi l e.
UNI X System ANSI Compi l er mexopts.sh
GCC gccopts.sh
System C++ Compi l er cxxopts.sh
Table 2-3: Options Files Path
Platform Location
UNI X <matlab>/bin
Wi ndows <matlab>\bin
Table 2-2: Options Files (Continued)
Platform Compiler Options File
Building MEX-Files
2-11
Al ternati vel y, you do not have to copy the opti ons fi l e to the MEX-fi l e creati on
di rectory; you can speci fy the opti ons fi l ename, i ncl udi ng the ful l path, i n the
opti ons fi l ename.
Note: Chapter 8 contai ns speci fi c i nformati on on how to modi fy opti ons fi l es
for parti cul ar systems.
2 Getting Started
2-12
Troubleshooting Your Configuration
Thi s secti on focuses on some common probl ems that mi ght occur when creati ng
MEX-fi l es.
Search Path Problem on Windows
Under Wi ndows, i f you move the MATLAB executabl e wi thout rei nstal l i ng
MATLAB, you may need to modi fy mex.bat to poi nt to the new MATLAB
l ocati on.
MATLAB Pathnames Containing Spaces on Windows
I f you have probl ems bui l di ng MEX-fi l es on Wi ndows and there i s a space i n
any of the di rectory names wi thi n the MATLAB path, you need to ei ther
rei nstal l MATLAB i nto a pathname that contai ns no spaces or rename the
di rectory that contai ns the space. For exampl e, i f you i nstal l MATLAB under
the Program Files di rectory, you may have di ffi cul ty bui l di ng MEX-fi l es. Al so,
i f you i nstal l MATLAB i n a di rectory such as MATLAB V5.2, you may have
di ffi cul ty.
DLLs Not on Path on Windows
MATLAB wi l l fai l to l oad MEX-fi l es i f i t cannot fi nd al l DLLs referenced by the
MEX-fi l e; the DLLs must be on the DOS path or i n the same di rectory as the
MEX-fi l e. Thi s i s al so true for thi rd-party DLLs.
Non-ANSI Compiler on UNIX
On the Sun OS 4.1.* pl atform, the bundl ed compi l er i s not ANSI ; you must
acqui re a supported ANSI compi l er. The same i s true on the HP-700; you must
acqui re a supported ANSI compi l er.
General Configuration Problem
Make sure you fol l owed the confi gurati on steps for your pl atform descri bed i n
thi s chapter. Al so, refer to Chapter 8, System Setup, for addi ti onal
i nformati on.
3
Creati ng C Language
MEX-Fi l es
C MEX-Files . . . . . . . . . . . . . . . . . . . . 3-2
The Parts of a MEX-Fi l e . . . . . . . . . . . . . . . . 3-2
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
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 fr om 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
Howto DebugC LanguageMEX-Files . . . . . . . . 3-41
Debuggi ng on UNI X . . . . . . . . . . . . . . . . . 3-41
Debuggi ng on Wi ndows . . . . . . . . . . . . . . . . 3-42
3 Creating C Language MEX-Files
3-2
C MEX-Files
C MEX-fi l es are bui l t by usi ng the mex scri pt to compi l e your C source code wi th
addi ti onal cal l s to API routi nes.
Directory Organization
A col l ecti on of fi l es associ ated wi th the creati on of C l anguage MEX-fi l es i s
l ocated on your di sk. Thi s tabl e l i sts the l ocati on of these fi l es.
Appendi x B, Di rectory Organi zati on, descri bes the contents of the
API -rel ated di rectori es and fi l es.
The Parts of a MEX-File
The source code for a 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
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.
I n the gateway routi ne, you can access the data i n the mxArray structure and
then mani pul ate thi s data i n your C computati onal subrouti ne. For exampl e,
the expressi on mxGetPr(prhs[0]) returns a poi nter of type double * to the real
data i n the mxArray poi nted to by prhs[0]. You can then use thi s poi nter l i ke
any other poi nter of type double * i n C. After cal l i ng your C computati onal
Platform Directory
Wi ndows <matlab>\extern
UNI X <matlab>/extern
where:
<matlab> i s the MATLAB root di rectory
C MEX-Files
3-3
routi ne from the gateway, you can set a poi nter of type mxArray to the data i t
returns. MATLAB i s then abl e to recogni ze the output from your computati onal
routi ne as the output from the MEX-fi l e.
Fi gure 3-1 shows how i nputs enter a MEX-fi l e, what functi ons the gateway
functi on performs, and how outputs return to MATLAB.
3 Creating C Language MEX-Files
3-4
Figure 3-1: C MEX Cycle
const mxArray *A
A = prhs[0]
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.
mxArray *C
C = plhs[0]
const mxArray *B
B = prhs[1]
mxArray *D
D = plhs[1]
INPUTS
OUTPUTS
func.c
void mexFunction(
int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
I n the gateway routi ne:
Use the mxCreate functi ons to create
the MATLAB arrays for your output
arguments. Set plhs[0], [1], to the
poi nters to the newl y created
MATLAB arrays.
Use the mxGet functi ons to extract
your data from prhs[0], [1],
Cal l your C subrouti ne passi ng the
i nput and output data poi nters as
functi on parameters.
MATLAB
On return from
MEX-fi l e func:
[C,D]=func(A,B)
plhs[0] i s assi gned
to C and plhs[1] i s
assi gned to D.
C MEX-Files
3-5
Required Arguments to a MEX-File
The two components of the MEX-fi l e may be separate or combi ned. I n ei ther
case, the fi l es must contai n the #include "mex.h" header so that the entry
poi nt and i nterface routi nes are decl ared properl y. The name of the gateway
routi ne must al ways be mexFunction and must contai n these parameters:
void mexFunction(
int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
/* more C code ... */
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. 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.
The par ameter s plhs and prhs are vectors that contai n poi nters to the l eft- and
ri ght-hand arguments of the MEX-fi l e. Note that both are decl ared as
contai ni ng type mxArray *, whi ch means that the vari abl es poi nted at are
MATLAB arrays. prhs i s a l ength nrhs array of 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 wi l l contai n
poi nters to the l eft-hand si de outputs that your functi on generates. For
exampl e, i f you i nvoke a MEX-fi l e from the MATLAB workspace wi th the
command
x = fun(y,z);
3 Creating C Language MEX-Files
3-6
the MATLAB i nterpreter cal l s mexFunction wi th the arguments
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 par ameter 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[0]. I f plhs[0] 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.
nlhs = 1
nrhs = 2
plhs
prhs

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

cal l backs.) For exampl e, the sampl e control shi pped wi th


MATLAB has the fol l owi ng methods, properti es, and events:
Methods
Redraw - causes the control to redraw
Beep - causes the control to beep
AboutBox - di spl ay the control s About di al og
Properties
Radius (i nteger) - sets the radi us of the ci rcl e drawn by the control
Label (stri ng) - text to be drawn i n the control
MATLAB ActiveX Integration
7-3
Events
Click - fi r ed when the user cl i cks on the control
One i mportant characteri sti c of COM i s that i t defi nes an object model i n whi ch
objects support mul ti pl e i nterfaces. Some i nterfaces are standard i nterfaces,
whi ch are defi ned by Mi crosoft and are part of Acti veX, and some i nterfaces are
customi nterfaces, whi ch are defi ned by i ndi vi dual component vendors. I n
order to use any Acti veX object, you must l earn about whi ch custom i nterfaces
i t supports, and the i nterfaces methods, properti es, and events. The Acti veX
objects vendor provi des thi s i nformati on.
MATLAB ActiveX Support Overview
MATLAB supports two Acti veX technol ogi es: Acti veX control contai nment and
Acti veX Automati on. Acti veX control s are appl i cati on components that can be
both vi sual l y and programmati cal l y i ntegrated i nto an Acti veX control
contai ner, such as MATLAB fi gure wi ndows. Some exampl es of useful Acti veX
control s are the Mi crosoft I nternet Expl orer Web Browser control , the
Mi crosoft Wi ndows Communi cati ons control for seri al port access, and the
graphi cal user i nterface control s del i vered wi th the Vi sual Basi c devel opment
envi ronment.
Acti veX Automati on al l ows MATLAB to both control and be control l ed by other
Acti veX components. When MATLAB i s control l ed by another component, i t i s
acti ng as an automati on server. When MATLAB control s another component,
MATLAB i s the automati on client, and the other component i s the automati on
server.
MATLAB automati on server capabi l i ti es i ncl ude the abi l i ty to execute
commands i n the MATLAB workspace, and to get and put matri ces di rectl y
from and i nto the workspace. MATLAB automati on cl i ent capabi l i ti es al l ow
MATLAB, through M-code, to programmati cal l y i nstanti ate and mani pul ate
automati on servers. The MATLAB automati on cl i ent capabi l i ti es are a subset
of the MATLAB control contai nment support, si nce you use the automati on
cl i ent capabi l i ti es to mani pul ate control s as wel l as automati on servers. I n
other words, al l Acti veX control s are Acti veX automati on servers, but not al l
automati on servers are necessari l y control s.
I n general , servers that are not control s wi l l not be physi cal l y or vi sual l y
embedded i n the cl i ent appl i cati on. (MATLAB i s a good exampl e MATLAB
i s not i tsel f a control , but i t i s a server. So, MATLAB cannot be physi cal l y
7 Client/Server Applications
7-4
embedded wi thi n another cl i ent. However, si nce MATLAB i s a control
container, other Acti veX control s can be embedded wi thi n MATLAB.)
I n addi ti on, MATLAB shi ps wi th a very si mpl e sampl e Acti veX control that
draws a ci rcl e on the screen and di spl ays some text. Thi s al l ows MATLAB users
to try out MATLABs Acti veX control support wi th a known control . For more
i nformati on, see the secti on, MATLAB Sampl e Control .
MATLAB ActiveX Client Support
I n order to use an Acti veX component wi th MATLAB or wi th any Acti veX
cl i ent, you fi rst need to consul t the documentati on for that object and fi nd out
the name of the object i tsel f (known as the ProgI D), as wel l as the names of
the i nterfaces, methods, properti es, and events that the object uses. Once you
have thi s i nformati on, you can i ntegrate that object wi th MATLAB by usi ng
the Acti veX cl i ent support.
Using ActiveX Objects
You create an Acti veX control or server i n MATLAB by creati ng an i nstance of
the MATLAB acti vex cl ass. Each i nstance represents one i nterface to the
object.
Note: Thi s book uses Acti veX to refer to the generi c Acti veX contr ol /ser ver
and acti vex to refer to the MATLAB cl ass/object.
Creating ActiveX Objects. There are two commands used to create acti vex objects
i ni ti al l y
Once you create an acti vex object that represents an i nterface, you can
mani pul ate i t by i nvoki ng methods on the object to perform vari ous acti ons.
actxcontrol Creates an Acti veX control .
actxserver Creates an Acti veX automati on server.
MATLAB ActiveX Integration
7-5
Manipulating the Interface. These methods are i mpl emented for the acti vex cl ass.
The creati on commands, actxcontrol and actxserver, both return a
MATLAB acti vex object, whi ch represents the defaul t i nterface for the object
that was created. However, these objects may have other i nterfaces. I t i s
possi bl e (and common) for i nterfaces to al so be obtai ned by i nvoki ng a method
on, or getti ng a property from, an exi sti ng i nterface. The Acti veX get and
invoke methods automati cal l y create and return new acti vex objects to
represent these addi ti onal i nterfaces.
When each i nterface i s no l onger needed, use the release method to rel ease the
i nter face. When the enti re control or ser ver i s no l onger needed, use the delete
command to del ete i t. See the secti on, Rel easi ng I nterfaces, for more detai l s.
ActiveX Client Reference
Thi s secti on contai ns the reference pages for the commands that create Acti veX
objects and mani pul ate thei r i nterfaces.
Method Description
invoke I nvokes a method on an i nterface or di spl ays a l i st of
methods.
set Sets a property on an i nterface.
get Gets a property val ue from an i nterface or di spl ays a
l i st of properti es.
propedit Asks the control to di spl ay i ts bui l t-i n property page.
release Rel eases an acti vex object.
send Di spl ays a l i st of events.
delete Del etes an acti vex object.
7 Client/Server Applications
7-6
actxcontrol
Purpose
Create an Acti veX control i n a fi gure wi ndow.
Syntax
h = actxcontrol (progid [, position [, handle ...
[,callback |{ event1 eventhandler1; ...
event2 eventhandler2; }]]])
Arguments
progid
Stri ng that i s the name of the control to create. The control vendor
provi des thi s stri ng.
position
Posi ti on vector contai ni ng the x and y l ocati on and the xsize and
ysize of the control , expr essed i n pi xel uni ts as [x y xsize ysize].
Defaul ts to [20 20 60 60].
handle
Handl e Graphi cs handl e of the fi gure wi ndow i n whi ch the control i s
to be created. I f the control shoul d be i nvi si bl e, use the handl e of an
i nvi si bl e fi gure wi ndow. Defaul ts to gcf.
callback
Name of an M-functi on that accepts a vari abl e number of arguments.
Thi s functi on wi l l be cal l ed whenever the control tri ggers an event.
Each argument i s converted to a MATLAB stri ng; the fi rst argument
i s al ways a stri ng that represents the numeri cal val ue of the event
that was tri ggered. These numeri cal val ues are defi ned by the control .
(See the secti on, Wri ti ng Event Handl ers, for more i nformati on on
handl i ng control events.)
event
Tri ggered event speci fi ed by ei ther number or name.
eventhandler
Name of an M-functi on that accepts a vari abl e number of arguments.
Thi s functi on wi l l be cal l ed whenever the control tri ggers the event
MATLAB ActiveX Integration
7-7
associ ated wi th i t. The fi rst argument i s the acti vex object, the second
number represents the numeri cal val ue of the event that was
tri ggered. Note that the second number i s not converted to a stri ng as
i s the case i n the cal l back M-fi l e styl e. These val ues are defi ned by
the control . See the secti on, Wri ti ng Event Handl ers, for more
i nformati on on handl i ng control events.
Note: There are two ways to handl e events. You can create a si ngl e
cal l back or you can speci fy a cel l array that contai ns pai rs of events
and event handl ers. I n the cel l array format, speci fy events by ei ther
number or name. Each control defi nes event numbers and names.
There i s no l i mi t to the number of pai rs that can be speci fi ed i n the cel l
array. Al though usi ng the si ngl e cal l back method may be easi er i n
some cases, usi ng the cel l array techni que creates more effi ci ent code
that resul ts i n better performance.
Returns
A MATLAB acti vex object that represents the defaul t i nterface for
thi s control or server. Use the get, set, invoke, propedit, release,
and delete methods on thi s object. A MATLAB error wi l l be
generated i f thi s cal l fai l s.
Description
Create an Acti veX control at a parti cul ar l ocati on wi thi n a fi gure
wi ndow. I f the parent fi gure wi ndow i s i nvi si bl e, the control wi l l be
i nvi si bl e. The returned MATLAB acti vex object represents the defaul t
i nterface for the control . Thi s i nterface must be rel eased through a
cal l to release when i t i s no l onger needed to free the memory and
resources used by the i nterface. Note that rel easi ng the i nterface does
not del ete the control i tsel f (use the delete command to del ete the
control .)
For an exampl e cal l back event handl er, see the fi l e sampev.m i n the
toolbox\matlab\winfun di rectory.
7 Client/Server Applications
7-8
Examples
Cal l back styl e:
f = figure ('pos', [100 200 200 200]);
% create the control to fill the figure
h = actxcontrol ('MWSAMP.MwsampCtrl.1', [0 0 200 200], ...
gcf, sampev)
Cel l array styl e:
h = actxcontrol ('SELECTOR.SelectorCtrl.l', ...
[0 0 200 200], f, {600 'myclick'; 601 'my2click'; ...
605 'mymoused'})
h = actxcontrol ('SELECTOR.SelectorCtrl.l', ...
[0 0 200 200], f, {'Click' 'myclick'; ...
'DblClick' 'my2click'; 'MouseDown' 'mymoused'})
where the event handl ers, myclick.m, my2click.m, and mymoused.m
are
function myclick(varargin)
disp('Single click function')
function my2click(varargin)
disp('Double click function')
function mymoused(varargin)
disp('You have reached the mouse down function')
disp('The X position is: ')
varargin(5)
disp('The Y position is: ')
varargin(6)
You can use the same event handl er for al l the events you want to
moni tor usi ng the cel l array pai rs. Response ti me wi l l be better than
usi ng the cal l back styl e.
For exampl e
h = actxcontrol('SELECTOR.SelectorCtrl.1', ...
[0 0 200 200], f, {'Click' 'allevents'; ...
'DblClick' 'allevents'; 'MouseDown' 'allevents'})
MATLAB ActiveX Integration
7-9
and allevents.m i s
function allevents(varargin)
if (varargin{2} = 600)
disp ('Single Click Event Fired')
elseif (varargin{2} = 601)
disp ('Double Click Event Fired')
elseif (varargin{2} = 605)
disp ('Mousedown Event Fired')
end
7 Client/Server Applications
7-10
actxserver
Purpose
Create an Acti veX automati on server and return an acti vex object for
the servers defaul t i nterface.
Syntax
h = actxserver (progid [, MachineName])
Arguments
progid
Thi s i s a stri ng that i s the name of the control to i nstanti ate. Thi s
stri ng i s provi ded by the control or server vendor and shoul d be
obtai ned from the vendors documentati on. For exampl e, the progid
for Mi crosoft Excel i s Excel.Application.
MachineName
Thi s i s the name of a remote machi ne on whi ch the server i s to be run.
Thi s argument i s opti onal and i s used onl y i n envi ronments that
support Di stri buted Component Object Model (DCOM) see bel ow.
Thi s can be an I P address or a DNS name.
Returns
An acti vex object that represents the servers defaul t i nterface. Use
the get, set, invoke, release, and delete methods on thi s object. A
MATLAB error wi l l be generated i f thi s cal l fai l s.
Description
Create an Acti veX automati on server and return a MATLAB acti vex
object that represents the servers defaul t i nterface. Local /Remote
servers di ffer from control s i n that they are run i n a separate address
space (and possi bl y on a separate machi ne) and are not part of the
MATLAB process. Addi ti onal l y, any user i nterface that they di spl ay
wi l l be i n a separate wi ndow and wi l l not be attached to the MATLAB
process. Exampl es of l ocal servers are Mi crosoft Excel and Mi crosoft
Word. Note that automati on servers do not use cal l backs or event
handl ers.
MATLAB ActiveX Integration
7-11
Example
% launches Microsoft Excel & makes main frame window visible
h = actxserver ('Excel.Application')
set (h, 'Visible', 1);
7 Client/Server Applications
7-12
invoke
Purpose
I nvoke a method on an objects i nterface and retri eve the return val ue
of the method, i f any, or di spl ay a l i st of methods.
Syntax
v = invoke (a [, 'methodname' [, arg1, arg2, ]])
Arguments
a
An acti vex object previ ousl y returned from actxcontrol, actxserver,
get, or invoke.
methodname
A stri ng that i s the name of the method to be i nvoked.
arg1, , argn
Arguments, i f any, requi red by the method bei ng i nvoked.
Returns
The val ue returned by the method or a l i st of methods (i f you use the
form invoke(a).) The data type of the val ue i s dependent upon the
speci fi c method bei ng i nvoked and i s determi ned by the speci fi c
control or server. I f the method returns an i nterface (descri bed i n
Acti veX documentati on as an interface, or an I dispatch*), thi s method
wi l l return a new MATLAB acti vex object that represents the
i nterface returned. See the secti on, Data Conversi ons, for a
descri pti on of how MATLAB converts Acti veX data types.
Description
I nvoke a method on an objects i nterface and retri eve the return val ue
of the method, i f any. (Some methods have no return val ue.)
MATLAB ActiveX Integration
7-13
Example
I nvoke a method:
f = figure ('pos', [100 200 200 200]);
% create the control to fill the figure
h = actxcontrol ('MWSAMP.MwsampCtrl.1', [0 0 200 200], f)
set (h, 'Radius', 100);
v = invoke (h, 'Redraw')
Di spl ay a l i st of methods:
invoke(h)
AboutBox = Void AboutBox ()
ShowPropertyPage = Void ShowPropertyPage ()
7 Client/Server Applications
7-14
set
Purpose
Set an i nterface property to a speci fi c val ue.
Syntax
set (a [, 'propertyname' [, value [, arg1, arg2, ]]])
Arguments
a
An acti vex object handl e previ ousl y returned from actxcontrol,
actxserver, get, or invoke.
propertyname
A stri ng that i s the name of the property to be set.
value
The val ue to whi ch the i nterface property i s set.
arg1, , argn
Arguments, i f any, requi red by the property. Properti es are si mi l ar to
methods i n that i t i s possi bl e for a property to have arguments.
Returns
There i s no return val ue from set.
Description
Set an i nterface property to a speci fi c val ue. See the secti on, Data
Conversi ons, for i nformati on on how MATLAB converts workspace
matri ces to Acti veX data types.
Example
f = figure ('pos', [100 200 200 200]);
% create the control to fill the figure
a = actxcontrol ('MWSAMP.MwsampCtrl.1', [0 0 200 200], f)
set (a, 'Label', 'Click to fire event');
set (a, 'Radius', 40);
invoke (a, 'Redraw');
MATLAB ActiveX Integration
7-15
get
Purpose
Retri eve a property val ue from an i nterface or get a l i st of properti es.
Syntax
v = get (a [, 'propertyname' [, arg1, arg2, ]])
Arguments
a
An acti vex object previ ousl y returned from actxcontrol, actxserver,
get, or invoke.
propertyname
A stri ng that i s the name of the property val ue to be retri eved.
arg1, , argn
Arguments, i f any, requi red by the property bei ng retri eved.
Properti es are si mi l ar to methods i n that i t i s possi bl e for a property
to have arguments.
Returns
The val ue of the property or a l i st of properti es (i f you use the form
get(a)). The meani ng and type of thi s val ue i s dependent upon the
speci fi c property bei ng retri eved. The objects documentati on shoul d
descri be the speci fi c meani ng of the return val ue. See the secti on,
Data Conversi ons, for a descri pti on of how MATLAB converts
Acti veX data types.
Description
Retri eve a property val ue from an i nterface.
Note: You can use the return val ue of actxcontrol as an argument
to the get functi on to get a l i st of pr operti es of the control and methods
that can be i nvoked.
7 Client/Server Applications
7-16
Examples
Retri eve a si ngl e, property val ue:
% get the string value of the 'Label' property
s = get (a, 'Label');
Retri eve a l i st of properti es:
get(a)
AutoAlign = [1]
AutoAngle = [1]
AutoAngleConfine = [0]
AutoOffset = [1]
.
.
.
SelectionOffsetY = [0]
SelectionRadius = [0.8]
Selections = [4]
Value = [0]
MATLAB ActiveX Integration
7-17
propedit
Purpose
Request the control to di spl ay i ts bui l t-i n property page.
Syntax
propedit (a)
Arguments
a
An i nterface handl e previ ousl y returned from actxcontrol, get, or
invoke.
Description
Request the control to di spl ay i ts bui l t-i n property page. Note that
some contr ol s do not have a bui l t-i n pr operty page. For those objects,
thi s command wi l l fai l .
Example
propedit (a)
7 Client/Server Applications
7-18
release
Purpose
Rel eases an i nterface.
Syntax
release (a)
Arguments
a
Acti vex object that represents the i nterface to be rel eased.
Description
Rel ease the i nterface and al l resources used by the i nterface. Each
i nterface handl e must be rel eased when you are fi ni shed
mani pul ati ng i ts properti es and i nvoki ng i ts methods. Once an
i nterface has been rel eased, i t i s no l onger val i d and subsequent
Acti veX operati ons on the MATLAB object that represents that
i nterface wi l l resul t i n errors.
Note: Rel easi ng the i nterface wi l l not del ete the control i tsel f (see
delete), si nce other i nterfaces on that object may sti l l be acti ve. See
the secti on, Rel easi ng I nterfaces, for more i nformati on.
Example
release (a)
MATLAB ActiveX Integration
7-19
send
Purpose
Returns a l i st of events that the control can tri gger.
Syntax
send (a)
Arguments
a
Acti vex object returned by actxcontrol.
Description
Di spl ays a l i st of events that control s send.
Example
send (a)
Change = Void Change ()
Click = Void Click ()
DblClick = Void DblClick ()
KeyDown = Void KeyDown (Variant(Pointer), Short)
KeyPress = Void KeyPress (Variant(Pointer), Short)
KeyUp = Void KeyUp (Variant(Pointer), Short)
MouseDown = Void MouseDown (Short, Short, Vendor-Defined,
Vendor-Defined)
MouseMove = Void MouseMove (Short, Short, Vendor-Defined,
Vendor-Defined)
MouseUp = Void MouseUp (Short, Short, Vendor-Defined,
Vendor-Defined)
7 Client/Server Applications
7-20
delete
Purpose
Del ete an Acti veX control or server.
Syntax
delete (a)
Arguments
a
An acti vex object previ ousl y returned from actxcontrol, actxserver,
get, or invoke.
Description
Del ete an Acti veX control or server. Thi s i s di fferent than rel easi ng an
i nterface, whi ch rel eases and i nval i dates onl y that i nterface. delete
rel eases al l outstandi ng i nterfaces and del etes the acti vex server or
control i tsel f.
Example
delete (a)
MATLAB ActiveX Integration
7-21
Writing Event Handlers
Acti veX events are i nvoked when a control wants to noti fy i ts contai ner that
somethi ng of i nterest has occurred. For exampl e, many control s tri gger an
event when the user si ngl e-cl i cks on the control . I n MATLAB, when a control
i s created, you may opti onal l y suppl y a cal l back (al so known as an event
handler function) as the l ast argument to the actxcontrol command or a cel l
array that contai ns the event handl ers.
h = actxcontrol (progid [, position [, handle ...
[, callback | {event1 eventhandler1; event2 eventhandler2; }]]])
The event handl er functi on (callback) i s cal l ed whenever the control tri ggers
any event. The event handl er functi on must be an M-functi on that accepts a
vari abl e number of arguments of the fol l owi ng form:
function event (varargin)
if (str2num(vararg{1}) == 600)
disp ('Click Event Fired');
end
Al l arguments passed to thi s functi on are MATLAB stri ngs. The fi rst argument
to the event handl er i s a stri ng that represents the number of the event that
caused the event handl er to be cal l ed. The remai ni ng arguments are the val ues
passed by the control wi th the event. These val ues wi l l vary wi th the parti cul ar
event and control bei ng used. The l i st of events that control i nvocati ons and
thei r correspondi ng event numbers and parameters must be obtai ned from the
control s documentati on. I n order to use events wi th MATLAB, you wi l l need to
fi nd out the numeri cal val ues that the control uses for each event so that you
can use these i n the event handl er.
The event handl ers that are used i n the cel l array styl e are sl i ghtl y di fferent
than those used i n the cal l back styl e. The fi rst argument i n the cel l array styl e
i s a reference to the object i tsel f. The second argument i s the event number,
whi ch, unl i ke the cal l back styl e, i s not a stri ng that represents the number.
(Subsequent arguments vary dependi ng on the event.)
7 Client/Server Applications
7-22
These sampl e event handl ers, myclick.m, my2click.m, and mymoused.m
correspond to the actxcontrol exampl e.
function myclick(varargin)
disp('Single click function')
function my2click(varargin)
disp('Double click function')
function mymoused(varargin)
disp('You have reached the mouse down function')
disp('The X position is: ')
varargin(5)
disp('The Y position is: ')
varargin(6)
You can use the same event handl er for al l the events you want to moni tor
usi ng the cel l array pai rs. Response ti me wi l l be better than usi ng the cal l back
styl e.
For i nstance
h = actxcontrol('SELECTOR.SelectorCtrl.1', [0 0 200 200], f, ...
{'Click' 'allevents'; 'DblClick' 'allevents'; ...
'MouseDown' 'allevents'})
and allevents.m i s
function allevents(varargin)
if (varargin{2} = 600)
disp ('Single Click Event Fired')
elseif (varargin{2} = 601)
disp ('Double Click Event Fired')
elseif (varargin{2} = 605)
disp ('Mousedown Event Fired')
end
Note: MATLAB does not support event arguments passed by reference or
return val ues from events.
MATLAB ActiveX Integration
7-23
Additional ActiveX Client Information
Releasing Interfaces
Each Acti veX object can support one or more i nterfaces. I n MATLAB, an
i nterface i s represented by an i nstance of the acti vex cl ass. There are three
ways to get a val i d i nterface object i nto the MATLAB workspace:
Return val ue from actxcontrol/actxserver
Return val ue from a property vi a get
Return val ue from a method i nvocati on vi a invoke
I n each case, once the i nterface i s represented by an acti vex object i n the
workspace, i t must be rel eased when you are fi ni shed usi ng i t. Fai l ure to
rel ease i nterface handl es wi l l resul t i n memory and resources bei ng consumed.
Al ternati vel y, you can use the delete command on any val i d i nterface object,
and al l i nterfaces for that object wi l l automati cal l y be rel eased (and thus
i nval i dated), and the Acti veX server or control i tsel f wi l l be del eted.
MATLAB wi l l automati cal l y rel ease al l i nterfaces for an Acti veX control when
the fi gure wi ndow that contai ns that control i s del eted or cl osed. MATLAB wi l l
al so automati cal l y rel ease al l handl es for an Acti veX automati on server when
MATLAB i s shut down.
Using ActiveX Collections
Acti veX collections are a way to support groups of rel ated Acti veX objects that
can be i terated over. A col l ecti on i s i tsel f a speci al i nterface wi th a Count
property (read onl y), whi ch contai ns the number of i tems i n the col l ecti on, and
an Item method, whi ch al l ows you to retri eve a si ngl e i tem from the col l ecti on.
The Item method i s i ndexed, whi ch means that i t requi res an argument that
speci fi es whi ch i tem i n the col l ecti on i s bei ng requested. The data type of the
i ndex can be any data type that i s appropri ate for the parti cul ar col l ecti on and
i s speci fi c to the control or server that supports the col l ecti on. Al though i nteger
i ndi ces are common, the i ndex coul d just as easi l y be a stri ng val ue. Often, the
return val ue from the Item method i s i tsel f an i nterface. Li ke al l i nterfaces,
thi s i nterface shoul d be rel eased when you are fi ni shed wi th i t.
Thi s exampl e i terates through the members of a col l ecti on. Each member of the
col l ecti on i s i tsel f an i nterface (cal l ed Plot and represented by a MATLAB
acti vex object cal l ed hPlot.) I n parti cul ar, thi s exampl e i terates through a
7 Client/Server Applications
7-24
col l ecti on of Plot i nterfaces, i nvokes the Redraw method for each i nterface, and
then rel eases each i nterface.
hCollection = get (hControl, 'Plots');
for i=1:get (hCollection, 'Count')
hPlot = invoke (hCollection, 'Item', i);
invoke (hPlot, 'Redraw');
release (hPlot);
end;
release (hCollection);
Data Conversions
Si nce Acti veX defi nes a number of di fferent data formats and types, you wi l l
need to know how MATLAB converts data from acti vex objects i nto vari abl es
i n the MATLAB workspace. Data from acti vex objects must be converted:
When a property val ue i s retri eved
When a val ue i s returned from a method i nvocati on
Thi s chart shows how Acti veX data types are converted i nto vari abl es i n the
MATLAB workspace.
ActiveX Data Type MATLAB Variable
Stri ng
Fi l e Ti me
Error
Deci mal Date
MATLAB Stri ng
Currency
Hresul t
I nt/Unsi gned (2, 4, 8)
Bool
Scal ar Doubl e
Real (Si ngl e/Doubl e
Nul l
NaN
Preci si on)
MATLAB ActiveX Integration
7-25
Using MATLAB As a DCOM Server Client
Di stri buted Component Object Model (DCOM) i s an object di stri buti on
mechani sm that al l ows Acti veX cl i ents to use remote Acti veX objects over a
network. At the ti me of thi s wri ti ng, DCOM i s shi pped wi th NT4.0, and can be
obtai ned from Mi crosoft for Wi ndows 95.
ActiveX Data Type MATLAB Variable
Empty
Unknown
Voi d
Carray
Not Converted (error)
Userdefi ned
Bl ob
Stream
Storage
Streamed Object
Stored Object
Bl ob Object
CF
Vari ant
Cel l Array
Array of Vari ant
I Di spatch *
acti vex Object
Currency
Hresul t
I nt/Unsi gned (2, 4, 8)
Bool
Matri x of Doubl e
Real (Si ngl e/Doubl e
Array of
Ptr
Preci si on)
7 Client/Server Applications
7-26
MATLAB has been tested as a DCOM server wi th Wi ndows NT 4.0 onl y.
Addi ti onal l y, MATLAB can be used as a DCOM cl i ent wi th remote automati on
servers i f the operati ng system on whi ch MATLAB i s runni ng i s DCOM
enabl ed.
Note: I f you use MATLAB as a remote DCOM server, al l MATLAB wi ndows
wi l l appear on the remote machi ne.
MATLAB ActiveX Control Container Limitations
The fol l owi ng i s a l i st of l i mi tati ons of MATLAB Acti veX support:
MATLAB onl y supports i ndexed col l ecti ons.
Acti veX control s are not pri nted wi th fi gure wi ndows.
MATLAB does not support event arguments passed by reference.
MATLAB does not support returni ng val ues from event handl er functi ons.
The posi ti on vector of a control cannot be changed or queri ed.
MATLAB does not support method or event arguments passed by reference.
MATLAB Sample Control
MATLAB shi ps wi th a very si mpl e exampl e Acti veX control that draws a ci rcl e
on the screen, di spl ays some text, and fi res a cl i cked event when the user
cl i cks on the control . Thi s control makes i t easy to try out Acti veX control
support wi th a known control . The control can be created by runni ng the
mwsamp fi l e i n the winfun di rectory.
The control i s stored i n the MATLAB bin (executabl e) di rectory al ong wi th the
control s type l i brary (a bi nary fi l e used by Acti veX tool s to deci pher the
control s capabi l i ti es).
MATLAB ActiveX Automation Server Support
MATLAB on Mi crosoft Wi ndows supports Acti veX Automati on server
capabi l i ti es. Automati on i s an Acti veX protocol that al l ows one appl i cati on or
component (the control l er) to control another appl i cati on or component (the
server). Thus, MATLAB can be l aunched and control l ed by any Wi ndows
program that can be an Automati on Control l er. Some exampl es of appl i cati ons
MATLAB ActiveX Integration
7-27
that can be Automati on Control l ers are Mi crosoft Excel , Mi crosoft Access,
Mi crosoft Project, and many Vi sual Basi c and Vi sual C++ programs. Usi ng
Automati on, you can execute MATLAB commands, and get and put mxArrays
from and to the MATLAB workspace.
To use MATLAB as an automati on server, fol l ow steps 1 and 2.
1 Consul t the documentati on of your control l er to fi nd out how to i nvoke an
Acti veX Automati on server. The name of the MATLAB Acti veX object that
i s pl aced i n the regi stry i s Matlab.Application. Exactl y how you i nvoke the
MATLAB server depends on whi ch control l er you choose, but al l control l ers
requi re thi s name to i denti fy the server.
2 The Acti veX Automati on i nterface to MATLAB supports several methods,
whi ch are descri bed bel ow. Here i s a Vi sual Basi c code fragment that
i nvokes the MATLAB Automati on Execute method, and that works i n
Mi crosoft Excel or any other Vi sual Basi c or Vi sual Basi c for Appl i cati ons
(VBA)-enabl ed appl i cati on. The Execute method takes a command stri ng as
an argument and returns the resul ts as a stri ng. The command stri ng can
be any command that woul d normal l y be typed i n the command wi ndow; the
resul t contai ns any output that woul d have been pri nted to the command
wi ndow as a resul t of executi ng the stri ng, i ncl udi ng errors.
Dim MatLab As Object
Dim Result As String
Set MatLab = CreateObject("Matlab.Application")
Result = MatLab.Execute("surf(peaks)")
MATLAB ActiveX Automation Methods
Thi s secti on l i sts the methods that are supported by the MATLAB Automati on
Server. The data types for the arguments and return val ues are expressed as
Acti veX Automati on data types, whi ch are l anguage-i ndependent types
defi ned by the Acti veX Automati on protocol . For exampl e, BSTR i s a
wi de-character stri ng type defi ned as an Automati on type, and i s the same data
format used by Vi sual Basi c to store stri ngs. Any Acti veX-compl i ant control l er
shoul d support these data types, al though the detai l s of how you decl are and
mani pul ate these are control l er speci fi c.
7 Client/Server Applications
7-28
BSTR Execute([in] BSTR Command);
Thi s command accepts a si ngl e stri ng (Command), whi ch contai ns any command
that can be typed at the MATLAB command wi ndow prompt. MATLAB wi l l
execute the command and return the resul ts as a stri ng. Any fi gure wi ndows
generated by the command are di spl ayed on the screen as i f the command were
executed di rectl y from the command wi ndow or an M-fi l e. A Vi sual Basi c
exampl e i s
Dim MatLab As Object
Dim Result As String
Set MatLab = CreateObject("Matlab.Application")
Result = MatLab.Execute("surf(peaks)")
void GetFullMatrix(
[in] BSTR Name,
[in] BSTR Workspace,
[in, out] SAFEARRAY(double)* pr,
[in, out] SAFEARRAY(double)* pi);
Thi s method retri eves a ful l , one- or two-di mensi onal real or i magi nary
mxArray from the named workspace. The real and (opti onal ) i magi nary parts
are retri eved i nto separate arrays of doubl es.
Name. I denti fi es the name of the mxArray to be retri eved.
Workspace. I denti fi es the workspace that contai ns the mxArray. Use the
workspace name base to retri eve an mxArray from the defaul t MATLAB
workspace. Use the workspace name gl obal to put the mxArray i nto the gl obal
MATLAB workspace. The cal l er workspace does not have any context i n the
API when used outsi de of MEX-fi l es.
pr. Array of real s that i s di mensi oned to be the same si ze as the mxArray bei ng
retri eved. On return, thi s array wi l l contai n the real val ues of the mxArray.
pi. Array of real s that i s di mensi oned to be the same si ze as the mxArray bei ng
retri eved. On return, thi s array wi l l contai n the i magi nary val ues of the
mxArray. I f the requested mxArray i s not compl ex, an empty array must be
MATLAB ActiveX Integration
7-29
passed. I n Vi sual Basi c, an empty array i s decl ared as
Dim Mempty() as Double. A Vi sual Basi c exampl e of thi s method i s
Dim MatLab As Object
Dim Result As String
Dim MReal(1, 3) As Double
Dim MImag() As Double
Dim RealValue As Double
Dim i, j As Integer
rem We assume that the connection to MATLAB exists.
Result = MatLab.Execute("a = [1 2 3 4; 5 6 7 8;]")
Call MatLab.GetFullMatrix("a", "base", MReal, MImag)
For i = 0 To 1
For j = 0 To 3
RealValue = MReal(i, j)
Next j
Next i
void PutFullMatrix(
[in] BSTR Name,
[in] BSTR Workspace,
[in] SAFEARRAY(double) pr,
[in] SAFEARRAY(double) pi);
Thi s method puts a ful l , one- or two-di mensi onal real or i magi nary mxArray
i nto the named workspace. The real and (opti onal ) i magi nary parts are passed
i n through separate arrays of doubl es.
Name. I denti fi es the name of the mxArray to be pl aced.
Workspace. I denti fi es the workspace i nto whi ch the mxArray shoul d be pl aced.
Use the workspace name base to put the mxArray i nto the defaul t MATLAB
wor kspace. Use the wor kspace name gl obal to put the mxArray i nto the gl obal
MATLAB workspace. The cal l er workspace does not have any context i n the
API when used outsi de of MEX-fi l es.
pr. Array of real s that contai ns the real val ues for the mxArray.
pi. Array of real s that contai ns the i magi nary val ues for the mxArray. I f the
mxArray that i s bei ng sent i s not compl ex, an empty array must be passed for
7 Client/Server Applications
7-30
thi s parameter. I n Vi sual Basi c, an empty array i s decl ared as Dim Mempty()
as Double. A Vi sual Basi c exampl e of thi s method i s
Dim MatLab As Object
Dim MReal(1, 3) As Double
Dim MImag() As Double
Dim i, j As Integer
For i = 0 To 1
For j = 0 To 3
MReal(i, j) = I * j;
Next j
Next I
rem We assume that the connection to MATLAB exists.
Call MatLab.PutFullMatrix("a", "base", MReal, MImag)
Additional ActiveX Server Information
Launching the MATLAB ActiveX Server
For MATLAB to act as an automati on server, i t must be started wi th the
/Automation command l i ne argument. Mi crosoft Wi ndows does thi s
automati cal l y when an Acti veX connecti on i s establ i shed by a control l er.
However, i f MATLAB i s al ready runni ng and was l aunched without thi s
parameter, any request by an automati on control l er to connect to MATLAB as
a server wi l l cause Wi ndows to l aunch another i nstance of MATLAB wi th the
/Automation parameter. Thi s protects control l ers from i nterferi ng wi th any
i nteracti ve MATLAB sessi ons that may be runni ng.
Specifying a Shared or Dedicated Server
You can l aunch the MATLAB Automati on server i n one of two modes shared
or dedi cated. A dedi cated server i s dedi cated to a si ngl e cl i ent; a shared server
i s shared by mul ti pl e cl i ents.
The mode i s determi ned by the Program I D (ProgI D) used by the cl i ent to
l aunch MATLAB. The ProgI D, Matlab.Application, (or the versi on-speci fi c
ProgI D, Matlab.Application.5) speci fi es the defaul t mode, whi ch i s shared.
To speci fy a dedi cated server, use the ProgI D, Matlab.Application.Single,
(or the versi on-speci fi c ProgI D, Matlab.Application.Single.5). The term
Single refers to the number of cl i ents that may connect to thi s server.
MATLAB ActiveX Integration
7-31
Once MATLAB i s l aunched as a shared server, al l cl i ents that request a
connecti on to MATLAB by usi ng the shared server ProgI D wi l l connect to the
al ready runni ng i nstance of MATLAB. I n other words, there i s never more than
one i nstance of a shared server runni ng, si nce i t i s shared by al l cl i ents that use
the ProgI D that speci fi es a shared server.
Note: Cl i ents wi l l not connect to an i nteracti ve i nstance of MATLAB, that i s,
an i nstance of MATLAB that was l aunched manual l y and wi thout the
/Automation command l i ne fl ag.
Each cl i ent that requests a connecti on to MATLAB usi ng a dedi cated ProgI D
wi l l cause a separate i nstance of MATLAB to be l aunched, and that server wi l l
not be shared wi th any other cl i ent. Therefore, there can be several i nstances
of a dedi cated server runni ng si mul taneousl y, si nce the dedi cated server i s not
shared by mul ti pl e cl i ents.
Using MATLAB As a DCOM Server
DCOM i s a protocol that al l ows Acti veX connecti ons to be establ i shed over a
network. I f you are usi ng a versi on of Wi ndows that supports DCOM (Wi ndows
NT 4.0 at the ti me of thi s wri ti ng) and a control l er that supports DCOM, you
can use the control l er to l aunch MATLAB on a remote machi ne. To do thi s,
DCOM must be confi gured properl y, and MATLAB must be i nstal l ed on each
machi ne that i s used as a cl i ent or server. (Even though the cl i ent machi ne wi l l
not be runni ng MATLAB i n such a confi gurati on, the cl i ent machi ne must have
a MATLAB i nstal l ati on because certai n MATLAB components are requi red to
establ i sh the remote connecti on.) Consul t the DCOM documentati on for how to
confi gure DCOM for your envi ronment.
7 Client/Server Applications
7-32
Dynamic Data Exchange (DDE)
MATLAB provi des functi ons that enabl e MATLAB to access other Wi ndows
appl i cati ons and for other Wi ndows appl i cati ons to access MATLAB i n a wi de
range of contexts. These functi ons use dynami c data exchange (DDE), software
that al l ows Mi crosoft Wi ndows appl i cati ons to communi cate wi th each other by
exchangi ng data.
Thi s secti on descri bes these new DDE functi ons i n the fol l owi ng order:
DDE Concepts and Termi nol ogy
Accessi ng MATLAB As a Server
Usi ng MATLAB As a Cl i ent
DDE Advi sor y Li nks
DDE Concepts and Terminology
Appl i cati ons communi cate wi th each other by establ i shi ng a DDE
conversation. The appl i cati on that i ni ti ates the conversati on i s cal l ed the client.
The appl i cati on that responds to the cl i ent appl i cati on i s cal l ed the server.
When a cl i ent appl i cati on i ni ti ates a DDE conversati on, i t must i denti fy two
DDE parameters that are defi ned by the server:
The name of the appl i cati on i t i ntends to have the conversati on wi th, cal l ed
the servicename
The subject of the conversati on, cal l ed the topic
When a server appl i cati on recei ves a request for a conversati on i nvol vi ng a
supported topi c, i t acknowl edges the request, establ i shi ng a DDE conversati on.
The combi nati on of a servi ce and a topi c i denti fi es a conversati on uni quel y. The
servi ce or topi c cannot be changed for the durati on of the conversati on,
al though the servi ce can mai ntai n more than one conversati on.
Duri ng a DDE conversati on, the cl i ent and server appl i cati ons exchange data
concerni ng i tems. An itemi s a reference to data that i s meani ngful to both
appl i cati ons i n a conversati on. Ei ther appl i cati on can change the i tem duri ng
a conversati on. These concepts are di scussed i n more detai l bel ow.
Dynamic Data Exchange (DDE)
7-33
The Service Name
Every appl i cati on that can be a DDE server has a uni que servicename. The
servi ce name i s usual l y the appl i cati ons executabl e fi l ename wi thout any
extensi on. Servi ce names are not case sensi ti ve. Here are some commonl y used
servi ce names:
The servi ce name for MATLAB i s Matlab.
The servi ce name for Mi crosoft Word for Wi ndows i s WinWord.
The servi ce name for Mi crosoft Excel i s Excel.
For the servi ce names of other Wi ndows appl i cati ons, refer to the appl i cati on
documentati on.
The Topic
The topicdefi nes the subject of a DDE conversati on and i s usual l y meani ngful
to both the cl i ent and server appl i cati ons. Topi c names are not case sensi ti ve.
MATLAB topi cs are Systemand Engineand are di scussed bel ow i n the secti on,
Accessi ng MATLAB As a Server. Most appl i cati ons support the Systemtopi c
and at l east one other topi c. Consul t your appl i cati on documentati on for
i nformati on about supported topi cs.
The Item
Each topi c supports one or more i tems. An itemi denti fi es the data bei ng passed
duri ng the DDE conversati on. Case sensi ti vi ty of i tems depends on the
appl i cati on. MATLAB Enginei tems are case sensi ti ve i f they refer to matri ces
because matri x names are case sensi ti ve.
Clipboard Formats
DDE uses the Wi ndows cl i pboard formats for formatti ng data sent between
appl i cati ons. As a cl i ent, MATLAB supports onl y Text format. As a server,
MATLAB supports Text, Metafi l epi ct, and XLTabl e formats, descri bed bel ow.
Text Data i n Text format i s a buffer of characters termi nated by the null
character. Li nes of text i n the buffer are del i mi ted by a carri age return
l i ne-feed combi nati on. I f the buffer contai ns col umns of data, those col umns
are del i mi ted by the tab character. MATLAB supports Text format for
7 Client/Server Applications
7-34
obtai ni ng the resul ts of a remote EvalString command and requests for
matri x data. Al so, matri x data can be sent to MATLAB i n Text format.
Metafilepict Metafi l epi ct format i s a descri pti on of graphi cal data
contai ni ng the drawi ng commands for graphi cs. As a resul t, data stored i n
thi s format i s scal abl e and devi ce i ndependent. MATLAB supports
Metafi l epi ct format for obtai ni ng the resul t of a remote command that causes
some graphi c acti on to occur.
XLTable XLTabl e format i s the cl i pboard format used by Mi crosoft Excel
and i s supported for ease and effi ci ency i n exchangi ng data wi th Excel .
XLTabl e format i s a bi nary buffer wi th a header that descri bes the data hel d
i n the buffer. For a ful l descri pti on of XLTabl e format, consul t the Mi crosoft
Excel SDK documentati on.
Accessing MATLAB As a Server
A cl i ent appl i cati on can access MATLAB as a DDE server i n the fol l owi ng
ways, dependi ng on the cl i ent appl i cati on:
I f you are usi ng an appl i cati on that provi des functi ons or macros to conduct
DDE conversati ons, you can use these functi ons or macros. For exampl e,
Mi crosoft Excel , Word for Wi ndows, and Vi sual Basi c provi de DDE functi ons
or macros. For more i nformati on about usi ng these functi ons or macros, see
the appropri ate Mi crosoft documentati on.
I f you are creati ng your own appl i cati on, you can use the MATLAB Engi ne
Li brary or DDE di rectl y. For more i nformati on about usi ng the Engi ne
Li brary, see I nterprocess Communi cati on: The MATLAB Engi ne, i n
Chapter 6. For more i nformati on about usi ng DDE routi nes, see the
Microsoft Windows Programmers Guide.
The fi gure bel ow i l l ustrates how MATLAB communi cates as a server. DDE
functi ons i n the cl i ent appl i cati on communi cate wi th MATLABs DDE server
modul e. The cl i ents DDE functi ons can be provi ded by ei ther the appl i cati on
or the MATLAB Engi ne Li brary.
MATLAB
DDE Server
Modul e
Cl i ent Appl i cati on
DDE Functi ons
Conversati on
Dynamic Data Exchange (DDE)
7-35
The DDE Name Hierarchy
When you access MATLAB as a server, you must speci fy i ts servi ce name, topi c,
and i tem. The fi gure bel ow i l l ustrates the MATLAB DDE name hi erarchy.
Topi cs and i tems are descri bed i n more detai l bel ow.
MATLAB DDE Topics
MATLAB topi cs are Systemand Engine:
The Systemtopi c al l ows users to browse the l i st of topi cs provi ded by the
server, the l i st of Systemtopi c i tems provi ded by the server, and the formats
supported by the server. These i tems are descri bed i n more detai l bel ow.
The Enginetopi c al l ows users to use MATLAB as a server by passi ng i t a
command to execute, requesti ng data, or sendi ng data. These i tems are al so
descri bed i n more detai l bel ow.
MATLAB
System
Engine
SysItems
Format
Topics
EngEvalString
EngStringResult
EngFigureResult
<matrix name>
service
topics
items
7 Client/Server Applications
7-36
MATLAB System Topic Support. The MATLAB Systemtopi c supports these i tems:
SysI tems pr ovi des a tab-del i mi ted l i st of i tems suppor ted under the System
topi c (thi s l i st).
Format provi des a tab-del i mi ted l i st of stri ng names of al l the formats
supported by the server. MATLAB supports Text, Metafi l epi ct, and XLTabl e.
These formats are descri bed above i n the Cl i pboard Formats secti on.
Topics provi des a tab-del i mi ted l i st of the names of the topi cs supported by
MATLAB.
MATLAB Engine Topic Support. The MATLAB Enginetopi c supports three
operati ons that may be used by appl i cati ons wi th a DDE cl i ent i nterface. These
operati ons i ncl ude sendi ng commands to MATLAB for eval uati on, requesti ng
data from MATLAB, and sendi ng data to MATLAB.
SendingCommands toMATLAB for Evaluation Cl i ents send commands to
MATLAB usi ng the DDE execute operati on. The Enginetopi c supports DDE
execute i n two forms because some cl i ents requi re that you speci fy the i tem
name and the command to execute, whi l e others requi re onl y the command.
Where an i tem name i s requi red, use EngEvalString. I n both forms, the format
of the command must be Text. Most cl i ents defaul t to Text for DDE execute. I f
the format cannot be speci fi ed, i t i s probabl y Text. The tabl e shows a summary
of the DDE execute parameters.
RequestingData fromMATLAB Cl i ents request data from MATLAB usi ng
the DDE request operati on. The Enginetopi c supports DDE requests for three
functi ons: text that i s the resul t of the previ ous DDE execute command,
graphi cal resul ts of the previ ous DDE execute command, and the data for a
speci fi ed matri x.
You request the stri ng resul t of a DDE execute command usi ng the
EngStringResult i tem wi th Text for mat.
Item Format Command
EngEvalString Text Stri ng
null Text Stri ng
Dynamic Data Exchange (DDE)
7-37
You request the graphi cal resul t of a DDE execute command usi ng the
EngFigureResult i tem. The EngFigureResult i tem can be used wi th Text or
Metafi l epi ct formats.
Speci fyi ng the Text format resul ts i n a stri ng havi ng a val ue of yes or no.
I f the resul t i s yes, the metafi l e for the current fi gure i s pl aced on the
cl i pboard. Thi s functi onal i ty i s provi ded for DDE cl i ents that can retri eve
onl y text from DDE requests, such as Word for Wi ndows. I f the resul t i s no,
no metafi l e i s pl aced on the cl i pboard.
Speci fyi ng the Metafi l epi ct format when there i s a graphi cal resul t causes a
metafi l e to be returned di rectl y from the DDE request.
You request the data for a matri x by speci fyi ng the name of the matri x as the
i tem. You can speci fy ei ther the Text or XLTabl e for mat.
The tabl e shows a summary of the DDE request parameters.
SendingDatatoMATLAB Cl i ents send data to MATLAB usi ng the DDE poke
operati on. The Enginetopi c supports DDE poke for updati ng or creati ng new
matri ces i n the MATLAB workspace. The i tem speci fi ed i s the name of the
matri x to be updated or created. I f a matri x wi th the speci fi ed name al ready
exi sts i n the workspace i t wi l l be updated; otherwi se i t wi l l be created. The
matri x data can be i n Text or XLTabl e format.
Item Format Result
EngStringResult Text Stri ng
EngFigureResult Text Yes/No
EngFigureResult Metafi l epi ct Metafi l e of the current fi gure
<matrix name> Text Character buffer, tab-del i mi ted
col umns, CR/LF-del i mi ted rows
<matrix name> XLTabl e Bi nary data i n a format compati bl e
wi th Mi crosoft Excel
7 Client/Server Applications
7-38
The tabl e shows a summary of the DDE poke parameters.
Example: Using Visual Basic and the MATLAB DDE Server
Thi s exampl e shows a Vi sual Basi c form that contai ns two text edi t control s,
TextInput and TextOutput. Thi s code i s the TextInput_KeyPress method.
Sub TextInput_KeyPress(KeyAscii As Integer)
rem If the user presses the return key
rem in the TextInput control.
If KeyAscii = vbKeyReturn then
rem Initiate the conversation between the TextInput
rem control and MATLAB under the Engine topic.
rem Set the item to EngEvalString.
TextInput.LinkMode = vbLinkNone
TextInput.LinkTopic = "MATLAB|Engine"
TextInput.LinkItem = "EngEvalString"
TextInput.LinkMode = vbLinkManual
rem Get the current string in the TextInput control.
rem This text is the command string to send to MATLAB.
szCommand = TextInput.Text
rem Perform DDE Execute with the command string.
TextInput.LinkExecute szCommand
TextInput.LinkMode = vbLinkNone
Item Format Poke Data
<matrix name> Text Character buffer, tab-del i mi ted
col umns, CR/LF-del i mi ted rows
<matrix name> XLTabl e Bi nary data i n a format compati bl e
wi th Mi crosoft Excel
Dynamic Data Exchange (DDE)
7-39
rem Initiate the conversation between the TextOutput
rem control and MATLAB under the Engine topic.
rem Set the item to EngStringResult.
TextOutput.LinkMode = vbLinkNone
TextOutput.LinkTopic = "MATLAB|Engine"
TextOutput.LinkItem = "EngStringResult"
TextOutput.LinkMode = vbLinkManual
rem Request the string result of the previous EngEvalString
rem command. The string ends up in the text field of the
rem control TextOutput.text.
TextOutput.LinkRequest
TextOutput.LinkMode = vbLinkNone
End If
End Sub
Using MATLAB As a Client
For MATLAB to act as a cl i ent appl i cati on, you can use the MATLAB DDE
cl i ent functi ons to establ i sh and mai ntai n conversati ons.
Thi s fi gure i l l ustrates how MATLAB communi cates as a cl i ent to a server
appl i cati on.
MATLAB
DDE Cl i ent
Modul e
Server Appl i cati on
Conversati on
DDE Server
Modul e
7 Client/Server Applications
7-40
MATLABs DDE cl i ent modul e i ncl udes a set of functi ons. Thi s tabl e descri bes
the functi ons that enabl e you to use MATLAB as a cl i ent.
I f the server appl i cati on i s Mi crosoft Excel , you can speci fy the Systemtopi c or
a topi c that i s a fi l ename. I f you speci fy the l atter, the fi l ename ends i n .XLS or
.XLC and i ncl udes the ful l path i f necessary. A Mi crosoft Excel i tem i s a cel l
reference, whi ch can be an i ndi vi dual cel l or a range of cel l s.
Mi crosoft Word for Wi ndows topi cs are Systemand document names that are
stored i n fi l es whose names end i n .DOC or .DOT. A Word for Wi ndows i tem i s
any bookmark i n the document speci fi ed by the topi c.
Function Description
ddeadv Sets up advi sory l i nk between MATLAB and DDE server
appl i cati on.
ddeexec Sends executi on stri ng to DDE server appl i cati on.
ddeinit I ni ti ates DDE conversati on between MATLAB and another
appl i cati on.
ddepoke Sends data from MATLAB to DDE server appl i cati on.
ddereq Requests data from DDE server appl i cati on.
ddeterm Termi nates DDE conversati on between MATLAB and server
appl i cati on.
ddeunadv Rel eases advi sory l i nk between MATLAB and DDE server
appl i cati on.
Dynamic Data Exchange (DDE)
7-41
The fol l owi ng exampl e i s an M-fi l e that establ i shes a DDE conversati on wi th
Mi crosoft Excel , and then passes a 20-by-20 matri x of data to Excel .
% Initialize conversation with Excel.
chan = ddeinit('excel', 'Sheet1');
% Create a surface of peaks plot.
h = surf(peaks(20));
% Get the z data of the surface
z = get(h, 'zdata');
% Set range of cells in Excel for poking.
range = 'r1c1:r20c20';
% Poke the z data to the Excel spread sheet.
rc = ddepoke(chan, range, z);
DDE Advisory Links
You can use DDE to noti fy a cl i ent appl i cati on when data at a server has
changed. For exampl e, i f you use MATLAB to anal yze data entered i n an Excel
spreadsheet, you can establ i sh a l i nk that causes Excel to noti fy MATLAB
when thi s data changes. You can al so establ i sh a l i nk that automati cal l y
updates a matri x wi th the new or modi fi ed spreadsheet data.
MATLAB supports two ki nds of advi sory l i nks, di sti ngui shed by the way i n
whi ch the server appl i cati on advi ses MATLAB when the data that i s the
subject of the i tem changes at the server.
A hot link causes the server to suppl y the data to MATLAB when the data
defi ned by the i tem changes.
A warmlink causes the server to noti fy MATLAB when the data changes but
suppl i es the data onl y when MATLAB requests i t.
You set up and rel ease advi sor y l i nks wi th the ddeadv and ddeunadv functi ons.
MATLAB onl y supports l i nks when MATLAB i s a cl i ent.
Thi s exampl e establ i shes a DDE conversati on between MATLAB, acti ng as a
cl i ent, and Mi crosoft Excel . The exampl e extends the exampl e i n the previ ous
secti on by creati ng a hot l i nk wi th Excel . The l i nk updates matri x z and
eval uates a cal l back when the range of cel l s changes. A push-button, user
i nterface control termi nates the advi sory l i nk and the DDE conversati on when
7 Client/Server Applications
7-42
pressed. (For more i nformati on about creati ng a graphi cal user i nterface, see
the MATLAB manual BuildingGUI s with MATLAB.)
% Initialize conversation with Excel.
chan = ddeinit('excel', 'Sheet1');
% Set range of cells in Excel for poking.
range = 'r1c1:r20c20';
% Create a surface of peaks plot.
h = surf(peaks(20));
% Get the z data of the surface.
z = get(h, 'zdata');
% Poke the z data to the Excel spread sheet.
rc = ddepoke(chan, range, z);
% Set up a hot link ADVISE loop with Excel
% and the MATLAB matrix 'z'.
% The callback sets the zdata and cdata for
% the surface h to be the new data sent from Excel.
rc = ddeadv(chan, range,...
'set(h,''zdata'',z);set(h,''cdata'',z);','z');
% Create a push button that will end the ADVISE link,
% terminate the DDE conversation,
% and close the figure window.
c = uicontrol('String','&Close','Position',[5 5 80 30],...
'Callback',...
'rc = ddeunadv(chan,range);ddeterm(chan);close;');
8
System Setup
CustomBuildingMEX-Files . . . . . . . . . . . . . 8-2
UNI X . . . . . . . . . . . . . . . . . . . . . . . 8-5
Wi ndows . . . . . . . . . . . . . . . . . . . . . . 8-7
Troubleshooting . . . . . . . . . . . . . . . . . . 8-11
MEX-Fi l e Creati on . . . . . . . . . . . . . . . . . . 8-11
Understandi ng MEX-Fi l e Probl ems . . . . . . . . . . . 8-12
Memory Management Compati bi l i ty I ssues . . . . . . . . 8-16
8 System Setup
8-2
Custom Building MEX-Files
Thi s secti on di scusses i n detai l the process that the MEX-fi l e bui l d scri pt uses.
I n general , the defaul ts that come wi th MATLAB shoul d be suffi ci ent for
bui l di ng most MEX-fi l es. There are reasons that you mi ght need more detai l ed
i nformati on, such as:
You want to use an I ntegrated Devel opment Envi ronment (I DE), rather than
the provi ded scri pt, to bui l d MEX-fi l es.
You want to create a new opti ons fi l e, for exampl e, to use a compi l er that i s
not di rectl y supported.
You want to exerci se more control over the bui l d process than the scri pt uses.
The scr i pt, i n general , uses two stages (or thr ee, for Mi cr osoft Wi ndows) to
bui l d MEX-fi l es. These are the compi l e stage and the l i nk stage. I n between
these two stages, Wi ndows compi l ers must perform some addi ti onal steps to
prepare for l i nki ng (the prel i nk stage).
The mex scri pt has a set of swi tches that you can use to modi fy the l i nk and
compi l e stages. Tabl e 8-1 l i sts the avai l abl e swi tches and thei r uses.
Table 8-1: MEX Script Switches
Switch Function
argcheck Perform argument checki ng on MATLAB API
functi ons (C functi ons onl y).
c Compi l e onl y; do not l i nk.
D<name>[=<def>] (UNI X) Defi ne C preprocessor macro <name> [as
havi ng val ue <def>].
D<name> (Wi ndows) Defi ne C preprocessor macro <name>.
f <file> (UNI X and Wi ndows) Use <file> as the opti ons fi l e;
<file> i s a ful l pathname i f i t i s not i n current
di rectory. (On Wi ndows, not necessary i f you use the
setup opti on.)
Custom Building MEX-Files
8-3
F <file> (UNI X) Use <file> as the opti ons fi l e. <file> i s
searched for i n the fol l owi ng order:
The fi l e that occurs fi rst i n thi s l i st i s used:
./<filename>
$HOME/matlab/<filename>
$TMW_ROOT/bin/<filename>
F <file> (Wi ndows) Use <file> as the opti ons fi l e. (Not
necessary i f you use the setup opti on.) <file> i s
searched for i n the current di rectory fi rst and then
i n the same di rectory as mex.bat.
g Bui l d an executabl e wi th debuggi ng symbol s
i ncl uded.
h[elp] Hel p; l i sts the swi tches and thei r functi ons.
I<pathname> I ncl ude <pathname> i n the compi l er include search
path.
l<file> (UNI X) Li nk agai nst l i brary lib<file>.
L<pathname> (UNI X) I ncl ude <pathname> i n the l i st of di rectori es
to search for l i brari es.
<name>=<def> (UNI X) Overri de opti ons fi l e setti ng for vari abl e
<name>.
n No execute fl ag. Usi ng thi s opti on causes the
commands that woul d be used to compi l e and l i nk
the target to be di spl ayed wi thout executi ng them.
output <name> Create an executabl e named <name>. (An
appropri ate executabl e extensi on i s automati cal l y
appended.)
O Bui l d an opti mi zed executabl e.
Table 8-1: MEX Script Switches (Continued)
Switch Function
8 System Setup
8-4
For customi zi ng the bui l d process, you shoul d modi fy the opti ons fi l e, whi ch
contai ns the compi l er-speci fi c fl ags correspondi ng to the general compi l e,
prel i nk, and l i nk steps requi red on your system. The opti ons fi l e consi sts of a
seri es of vari abl e assi gnments; each vari abl e represents a di fferent l ogi cal
pi ece of the bui l d process.
Locating the Default Options File
For UNI X, the defaul t opti ons fi l e provi ded wi th MATLAB i s l ocated i n
<matlab>/bin. For Wi ndows, the defaul t opti ons fi l e i s i n <matlab>\bin.
On UNI X, the mex scri pt wi l l l ook for an opti ons fi l e cal l ed mexopts.sh i n the
current di rectory fi rst. I t searches next i n your $HOME/matlab di rectory, and
fi nal l y i n <matlab>/bin. On Wi ndows, the mex scri pt assumes that the opti ons
fi l e, mexopts.bat, i s i n the same di rectory as mex.bat, i .e., <matlab>\bin. On
both pl atforms, you can di rectl y speci fy the name of the opti ons fi l e usi ng the
f swi tch.
For speci fi c i nformati on on the defaul t setti ngs for the MATLAB supported
compi l ers, you can exami ne the opti ons fi l e i n <matlab>/bin/mexopts.sh
(<matlab>\bin\mexopts.bat i n Wi ndows), or you can i nvoke the mex scri pt i n
verbose mode.
The fol l owi ng secti on provi des addi ti onal detai l s regardi ng each of these
stages. However, there i s a general way to obtai n speci fi cs on the bui l d process,
whi ch i s the verbose opti on to the mex scri pt (the v fl ag). Thi s wi l l pri nt the
exact compi l er opti ons, prel i nk commands (i f appropri ate), and l i nker opti ons
used. The fol l owi ng secti on gi ves an over vi ew of the hi gh-l evel process; for
setup (Wi ndows) Set up defaul t opti ons fi l e. Thi s swi tch
shoul d be the onl y argument passed.
U<name> (UNI X and Wi ndows) Undefi ne C preprocessor
macro <name>.
V4 Compi l e MATLAB 4-compati bl e MEX-fi l es.
v Verbose; pri nt al l compi l er and l i nker setti ngs.
Table 8-1: MEX Script Switches (Continued)
Switch Function
Custom Building MEX-Files
8-5
exact fl ags provi ded for each compi l er, i nvoke the mex scri pt wi th the verbose
fl ag.
UNIX
On UNI X systems, there are two stages i n MEX-fi l e bui l di ng: compi l i ng and
l i nki ng. The compi l e stage must:
Add <matlab>/extern/include to the l i st of di rectori es i n whi ch to fi nd
header fi l es (I<matlab>/extern/include)
Defi ne the preprocessor macro MATLAB_MEX_FILE (DMATLAB_MEX_FILE)
(C MEX-fi l es onl y) Compi l e the source fi l e, whi ch contai ns versi on
i nformati on for the MEX-fi l e, <matlab>/extern/src/mexversion.c
For al l pl atforms except SunOS 4.x, the l i nk stage must:
I nstruct the l i nker to bui l d a shared l i brary
Li nk al l objects from compi l ed source fi l es (i ncl udi ng mexversion.c)
(Fortran MEX-fi l es onl y) Li nk i n the precompi l ed versi oni ng source fi l e,
<matlab>/extern/lib/$Arch/version4.o
Export the symbol s mexFunction and mexVersion (these symbol s represent
functi ons cal l ed by MATLAB)
For Fortran MEX-fi l es, the symbol s are al l l ower case and may have appended
underscores. For speci fi c i nformati on, i nvoke the mex scri pt i n verbose mode
and exami ne the output.
On the SunOS 4.x pl atform, the l i nk stage i s more compl i cated. The mex scri pt
does a test run of the l i nker to see what l i brari es need to be l i nked i n, and what
fl ags need to be used. The output of the test run, and the fi nal fl ags and
l i brari es used, are di fferent for each compi l er and compi l er versi on. However,
they are di spl ayed i n the verbose output.
For customi zi ng the bui l d process, you shoul d modi fy the opti ons fi l e. The
opti ons fi l e contai ns the compi l er-speci fi c fl ags correspondi ng to the general
steps outl i ned above. The opti ons fi l e consi sts of a ser i es of var i abl e
assi gnments; each vari abl e represents a di fferent l ogi cal pi ece of the bui l d
process. The opti ons fi l es provi ded wi th MATLAB are l ocated i n <matlab>/bin.
8 System Setup
8-6
The mex scri pt l ooks for an opti ons fi l e cal l ed mexopts.sh fi rst i n the current
di rectory, then i n your $HOME/matlab di rectory, and fi nal l y i n <matlab>/bin.
You can al so di rectl y speci fy the name of the opti ons fi l e usi ng the f opti on.
To ai d i n provi di ng fl exi bi l i ty, there are two sets of opti ons i n the opti ons fi l e
that can be turned on and off wi th swi tches to the mex scri pt. These sets of
opti ons correspond to bui l di ng i n debug mode and bui l di ng i n opti mi zati on
mode. They are represented by the vari abl es DEBUGFLAGS and OPTIMFLAGS,
respecti vel y, one pai r for each dri ver that i s i nvoked (CDEBUGFLAGS for the C
compi l er, FDEBUGFLAGS for the Fortran compi l er, and LDDEBUGFLAGS for the
l i nker; si mi l arl y for the OPTIMFLAGS).
I f you bui l d i n opti mi zati on mode (the defaul t), the mex scri pt wi l l i ncl ude the
OPTIMFLAGS opti ons i n the compi l e and l i nk stages.
I f you bui l d i n debug mode, the mex scri pt wi l l i ncl ude the DEBUGFLAGS
opti ons i n the compi l e and l i nk stages, but wi l l not i ncl ude the OPTIMFLAGS
opti ons.
You can i ncl ude both sets of opti ons by speci fyi ng both the opti mi zati on and
debuggi ng fl ags to the mex scri pt (O and g, respecti vel y).
Asi de from these speci al vari abl es, the mex opti ons fi l e defi nes the executabl e
i nvoked for each of the three modes (C compi l e, Fortran compi l e, l i nk) and the
fl ags for each stage. You can al so provi de expl i ci t l i sts of l i brari es that must be
l i nked i n to al l MEX-fi l es contai ni ng source fi l es of each l anguage.
Custom Building MEX-Files
8-7
The vari abl es can be summed up as fol l ows:
For speci fi cs on the defaul t setti ngs for these vari abl es, you can
Exami ne the opti ons fi l e i n <matlab>/bin/mexopts.sh
(or the opti ons fi l e you are usi ng), or
I nvoke the mex scri pt i n verbose mode
Windows
There are three stages to MEX-fi l e bui l di ng for both C and Fortran on Wi ndows
compi l i ng, prel i nki ng, and l i nki ng. The compi l e stage must:
Set up paths to the compi l er usi ng the COMPILER (e.g., Watcom), PATH,
INCLUDE, and LIB envi ronment vari abl es. I f your compi l er al ways has the
envi ronment vari abl es set (e.g., i n AUTOEXEC.BAT), you can remark them out
i n the opti ons fi l e.
Defi ne the name of the compi l er, usi ng the COMPILER envi ronment vari abl e,
i f needed.
Defi ne the compi l er swi tches i n the COMPLFLAGS envi ronment vari abl e.
a The swi tch to create a DLL i s requi red for MEX-fi l es.
b For stand-al one programs, the swi tch to create an exe i s requi red.
c The c swi tch (compi l e onl y; do not l i nk) i s recommended.
d The swi tch to speci fy 8-byte al i gnment.
e Any other swi tch speci fi c to the envi ronment can be used.
Variable C Compiler Fortran Compiler Linker
Executabl e CC FC LD
Fl ags CFLAGS FFLAGS LDFLAGS
Opti mi zati on COPTIMFLAGS FOPTIMFLAGS LDOPTIMFLAGS
Debuggi ng CDEBUGFLAGS FDEBUGFLAGS LDDEBUGFLAGS
Addi ti onal l i brari es CLIBS FLIBS ----
8 System Setup
8-8
Defi ne preprocessor macro, wi th D, MATLAB_MEX_FILE i s requi red.
Set up opti mi zer swi tches and/or debug swi tches usi ng OPTIMFLAGS and
DEBUGFLAGS. These are mutual l y excl usi ve: the OPTIMFLAGS are the defaul t,
and the DEBUGFLAGS are used i f you set the g swi tch on the mex command
l i ne.
The prel i nk stage dynami cal l y creates i mport l i brari es to i mport the requi red
functi on i nto the MEX, MAT, or engi ne fi l e. Al l MEX-fi l es l i nk agai nst
MATLAB onl y. MAT stand-al one programs l i nk agai nst libmx.dll (array
access l i brary)and libmat.dll (MAT-functi ons). Engi ne stand-al one programs
l i nk agai nst libmx.dll (array access l i brary) and libeng.dll for engi ne
functi ons. MATLAB and each DLL have correspondi ng .def fi l es of the same
names l ocated i n the <matlab>\extern\include di rectory.
Fi nal l y, the l i nk stage must:
Defi ne the name of the l i nker i n the LINKER envi ronment vari abl e.
Defi ne the LINKFLAGS envi ronment vari abl e that must contai n:
- The swi tch to create a DLL for MEX-fi l es, or the swi tch to create an exe
for stand-al one programs.
- Export of the entry poi nt to the MEX-fi l e as mexFunction for C or
MEXFUNCTION@16 for Mi crosoft Fortran.
- The i mport l i brary(s) created i n the PRELINK_CMDS stage.
- Any other l i nk swi tch speci fi c to the compi l er that can be used.
Defi ne the l i nki ng opti mi zati on swi tches and debuggi ng swi tches i n
LINKEROPTIMFLAGS and LINKDEBUGFLAGS. As i n the compi l e stage, these two
are mutual l y excl usi ve: the defaul t i s opti mi zati on, and the g swi tch
i nvokes the debug swi tches.
Defi ne the l i nk-fi l e i denti fi er i n the LINK_FILE envi ronment vari abl e, i f
needed. For exampl e, Watcom uses file to i denti fy that the name fol l owi ng
i s a fi l e and not a command.
Defi ne the l i nk-l i brary i denti fi er i n the LINK_LIB envi ronment vari abl e, i f
needed. For exampl e, Watcom uses library to i denti fy the name fol l owi ng i s
a l i brary and not a command.
Opti onal l y, set up an output i denti fi er and name wi th the output swi tch i n
the NAME_OUTPUT envi ronment vari abl e. The envi ronment vari abl e MEX_NAME
contai ns the name of the fi rst program i n the command l i ne. Thi s must be set
Custom Building MEX-Files
8-9
for output to work. I f thi s envi ronment i s not set, the compi l er defaul t i s to
use the name of the fi rst program i n the command l i ne. Even i f thi s i s set, i t
can be overri dden by speci fyi ng the mex output swi tch.
Linking DLLs to MEX-Files
To l i nk a DLL to a MEX-fi l e, l i st the DLL on the command l i ne and make sure
that the PRELINK_DLLS command i s properl y compl eted i n the opti ons fi l e. The
PRELINK_DLLS command dynami cal l y creates an i mport l i brary from your DLL
so that the DLL can be l i nked wi th your MEX-fi l e. PRELINK_DLLS contai ns the
i mport l i brary creati on command and opti ons for your compi l er and uses the
vari abl e DLL_NAME, whi ch i s assi gned to the DLL name(s) provi ded on the
command l i ne.
Versioning MEX-Files
The mex scri pt can bui l d your MEX-fi l e wi th a resource fi l e that contai ns
versi oni ng and other essenti al i nformati on. The resource fi l e i s cal l ed
mexversion.rc and resi des i n the extern\include di rectory. To support
versi oni ng, there are two new commands i n the opti ons fi l es, RC_COMPILER and
RC_LINKER, to provi de the resource compi l er and l i nker commands. I t i s
assumed that:
I f a compi l er command i s gi ven, the compi l ed resource wi l l be l i nked i nto the
MEX-fi l e usi ng the standard l i nk command.
I f a l i nker command i s gi ven, the resource fi l e wi l l be l i nked to the MEX-fi l e
after i t i s bui l t usi ng that command.
Compiling MEX-Files with the Microsoft Visual C++ IDE
Note: Thi s secti on provi des i nformati on on how to compi l e MEX-fi l es i n the
Mi crosoft Vi sual C++ (MSVC) I DE; i t i s not total l y i ncl usi ve. Thi s secti on
assumes that you know how to use the I DE. I f you need more i nformati on on
usi ng the MSVC I DE, refer to the correspondi ng Mi crosoft documentati on.
8 System Setup
8-10
To bui l d MEX-fi l es wi th the Mi crosoft Vi sual C++ i ntegrated devel opment
envi ronment:
1 Create a project and i nsert your MEX source and mexversion.rc i nto i t.
2 Create a .DEF fi l e to export the MEX entry poi nt. For exampl e
LIBRARY MYFILE.DLL
EXPORTS mexFunction <-- for a C MEX-fi l e
or
EXPORTS MEXFUNCTION@16 <-- for a For tran MEX-fi l e
3 Add the .DEF fi l e to the project.
4 Create an i mport l i brary of MEX-functi ons from MATLAB.DEF usi ng the LIB
command. For exampl e
LIB /DEF:MATLAB\EXTERN\INCLUDE\MATLAB.DEF/OUT:mymeximports.lib
5 Add the i mport l i brary to the l i brary modul es i n the LINK setti ngs opti on.
6 Add the MATLAB include di rectory, MATLAB\EXTERN\INCLUDE to the
include path i n the Settings C/C++Preprocessor opti on.
7 Add MATLAB_MEX_FILE to the C/C++Preprocessor opti on by sel ecti ng
Settings from the Build menu, sel ecti ng C/C++, and then typi ng
,MATLAB_MEX_FILE after the l ast entry i n the Preprocessor definitions
fi el d.
8 To debug the MEX-fi l e usi ng the I DE, put MATLAB.EXE i n the Settings
Debugopti on as the Executablefor debugsession.
Troubleshooting
8-11
Troubleshooting
MEX-File Creation
Use Fi gure 8-1 to hel p i sol ate di ffi cul ti es i n creati ng MEX-fi l es. The fol l owi ng
secti on, Understandi ng MEX-Fi l e Probl ems, provi des addi ti onal i nformati on
regardi ng common probl ems that occur when creati ng MEX-fi l es. I f the
suggesti ons i n these secti ons do not hel p, access the Sol uti ons Search Engi ne
at http://www.mathworks.com/solution.html.
8 System Setup
8-12
Figure 8-1: Troubleshooting MEX-File Creation Problems
Understanding MEX-File Problems
Thi s secti on contai ns i nformati on regardi ng common probl ems that occur when
creati ng MEX-fi l es. Probl ems 1 through 5 refer to speci fi c secti ons of the
Start
Acqui re a supported compi l er.
See SystemSetup for
Can you compi l e
and r un timestwo.c
or timestwo.f?
no Are you usi ng a
supported compi l er
?
no
Stop
yes
Doubl e check your
confi gurati on;
see SystemSetup.
yes
Can you compi l e
your pr ogram
?
no
Check for :
ANSI C code
Gener al C syntax er rors
yes
Can MATLAB
l oad your MEX-fi l e
?
no
Segmentati on faul t
or bus er ror
?
Use:
matlab check_malloc
1
Li nk agai nst al l l i br ari es
you i ntend to use.
Do you get
the ri ght answer
?
no
Use:
yes
yes
matlab check_malloc
1
Run i n debugger.
Stop
Check:
Spel l i ng of mexFunction
no
yes
1
UNI X onl y
mex argcheck
2
mexPrintf
1
2
3
4 5
2
MEX-fi l es onl y
detai l s.
Troubleshooting
8-13
previ ous fl owchart, and the remai ni ng secti ons refer to a parti cul ar pl atform
si tuati ons.
Problem 1
The most common confi gurati on probl em i n creati ng C MEX-fi l es on UNI X
i nvol ves usi ng a non-ANSI C compi l er, or fai l i ng to pass to the compi l er a fl ag
that tel l s i t to compi l e ANSI C code.
A rel i abl e way of knowi ng i f you have thi s type of confi gurati on probl em i s i f
the header fi l es suppl i ed by The MathWorks generate a stri ng of syntax errors
when you try to compi l e your code. See Bui l di ng MEX-Fi l es i n Chapter 2 for
i nformati on on sel ecti ng the appropri ate opti ons fi l e or, i f necessary, obtai n an
ANSI C compi l er.
Problem 2
A second way of generati ng a stri ng of syntax errors occurs when you attempt
to mi x ANSI and non-ANSI C code. The MathWorks provi des header and
source fi l es that are ANSI C compl i ant. Therefore, your C code must al so be
ANSI compl i ant.
Other common probl ems that can occur i n any C program are negl ecti ng to
i ncl ude al l necessary header fi l es, or negl ecti ng to l i nk agai nst al l requi red
l i brari es.
Problem 3
I f you recei ve an error of the form
Unable to load mex file:
??? Invalid MEXfile
MATLAB i s unabl e to recogni ze your MEX-fi l e as bei ng val i d.
MATLAB l oads MEX-fi l es by l ooki ng for the gateway routi ne, mexFunction. I f
you mi sspel l the functi on name, MATLAB i s not abl e to l oad your MEX-fi l e and
generates an error message. On Wi ndows, check that you are exporti ng
mexFunction correctl y.
On some pl atforms, i f you fai l to l i nk agai nst requi red l i brari es, you may get an
error when MATLAB l oads your MEX-fi l e rather than when you compi l e your
MEX-fi l e. I n such cases, you see a system error message referri ng to
8 System Setup
8-14
unresol ved symbol s or unresol ved references. Be sure to l i nk agai nst the
l i brary that defi nes the functi on i n questi on.
On Wi ndows, MATLAB wi l l fai l to l oad MEX-fi l es i f i t cannot fi nd al l DLLs
referenced by the MEX-fi l e; the DLLs must be on the path or i n the same
di rectory as the MEX-fi l e. Thi s i s al so true for thi rd party DLLs.
Problem 4
I f your MEX-fi l e causes a segmentati on vi ol ati on or bus error, i t means that the
MEX-fi l e has attempted to access protected, read-onl y, or unal l ocated memory.
Si nce thi s i s such a general category of programmi ng errors, such probl ems are
someti mes di ffi cul t to track down.
Segmentati on vi ol ati ons do not al ways occur at the same poi nt as the l ogi cal
errors that cause them. I f a program wri tes data to an uni ntended secti on of
memory, an error may not occur unti l the program reads and i nterprets the
corrupted data. Consequentl y, a segmentati on vi ol ati on or bus error can occur
after the MEX-fi l e fi ni shes executi ng.
MATLAB provi des three features to hel p you i n troubl eshooti ng probl ems of
thi s nature. Li sted i n order of si mpl i ci ty, they are:
Recompi l e your MEX-fi l e wi th argument checki ng (C MEX-fi l es onl y). You
can add a l ayer of error checki ng to your MEX-fi l e by recompi l i ng wi th the
mex scri pt fl ag argcheck. Thi s warns you about i nval i d arguments to both
MATLAB MEX-fi l e (mex) and matri x access (mx) API functi ons.
Al though your MEX-fi l e wi l l not run as effi ci entl y as i t can, thi s swi tch
detects such errors as passi ng null poi nters to API functi ons.
Run MATLAB wi th the check_malloc opti on (UNI X onl y). The MATLAB
startup fl ag, check_malloc, i ndi cates that MATLAB shoul d mai ntai n
addi ti onal memory checki ng i nformati on. When memory i s freed, MATLAB
Troubleshooting
8-15
checks to make sure that memory just before and just after thi s memory
remai ns unwri tten and that the memory has not been previ ousl y freed.
I f an error occurs, MATLAB reports the si ze of the al l ocated memory bl ock.
Usi ng thi s i nformati on, you can track down where i n your code thi s memory
was al l ocated, and proceed accordi ngl y.
Al though usi ng thi s fl ag prevents MATLAB from runni ng as effi ci entl y as i t
can, i t detects such errors as wri ti ng past the end of a di mensi oned array, or
freei ng previ ousl y freed memory.
Run MATLAB wi thi n a debuggi ng envi ronment. Thi s process i s al ready
descri bed i n the chapters on creati ng C and Fortran MEX-fi l es, respecti vel y.
Problem 5
I f your program generates the wrong answer(s), there are several possi bl e
causes. Fi rst, there coul d be an error i n the computati onal l ogi c. Second, the
program coul d be readi ng from an uni ni ti al i zed secti on of memory. For
exampl e, readi ng the 11th el ement of a 10-el ement vector yi el ds unpredi ctabl e
resul ts.
Another possi bi l i ty for generati ng a wrong answer coul d be overwri ti ng val i d
data due to memory mi shandl i ng. For exampl e, wri ti ng to the 15th el ement of
a 10-el ement vector mi ght overwri te data i n the adjacent vari abl e i n memory.
Thi s case can be handl ed i n a si mi l ar manner as segmentati on vi ol ati ons as
descri bed i n Probl em 4.
I n al l of these cases, you can use mexPrintf to exami ne data val ues at
i ntermedi ate stages, or run MATLAB wi thi n a debugger to expl oi t al l the tool s
the debugger provi des.
MEX-Files Created in Watcom IDE
I f you use the Watcom I DE to create MEX-fi l es and get unresol ved references
to API functi ons when l i nki ng agai nst our l i brari es, check the argument
passi ng conventi on. The Watcom I DE uses a defaul t swi tch that passes
parameters i n regi sters. MATLAB requi res that you pass parameters on the
stack.
8 System Setup
8-16
so_locations Error on SGI
When compi l i ng a MEX-fi l e under MATLAB 5 on SGI systems, you may get the
fol l owi ng errors:
ld error 48 cannot acces registry file so_locations no locks
available - ignored.
fatal 51 - can't assign virtual addresses for filename.mexsg
within specified range.
The l i nker creates a fi l e cal l ed so_locations. Thi s fi l e i s typi cal l y del eted,
however, i n some cases i t may not be del eted on your system. Del eti ng thi s fi l e
shoul d resol ve the probl em. However, i f the workaround does not sol ve the
probl em, try the fol l owi ng:
1 Move the fi l e you are tryi ng to compi l e to a /tmp di rectory.
2 Try compi l i ng the fi l e from thi s new l ocati on.
I f the fi l e compi l es i n the /tmp di rectory, there i s a probl em wi th your NFS
network confi gurati on. The probl em i s that ld (system l i nker) cannot pl ace
LOCKS fi l es on NFS dri ves. I f thi s i s the case, see your system admi ni strator and
make sure that LOCKD i s runni ng on your NFS server. For more i nformati on,
you may want to contact SGI di rectl y.
Memory Management Compatibility Issues
To address performance i ssues, we have made some changes to the i nternal
MATLAB memory management model . These changes wi l l al l ow us to provi de
future enhancements to the MEX-fi l e API .
As of MATLAB 5.2, MATLAB i mpl i ci tl y cal l s mxDestroyArray, the mxArray
destructor, at the end of a MEX-fi l es executi on on any mxArrays that are not
returned i n the l eft-hand si de l i st (plhs[]). You are now warned i f MATLAB
detects any mi sconstructed or i mproperl y destructed mxArrays.
We hi ghl y recommend that you fi x code i n your MEX-fi l es that produces any of
the warni ngs di scussed i n the fol l owi ng secti ons. For addi ti onal i nformati on,
see the secti on, Memory Management, i n Chapter 3.
Improperly Destroying an mxArray
You cannot use mxFree to destroy an mxArray.
Troubleshooting
8-17
Warning
Warning: You are attempting to call mxFree on a <class-id> array.
The destructor for mxArrays is mxDestroyArray; please call this
instead. MATLAB will attempt to fix the problem and continue, but
this will result in memory faults in future releases.
Note: Currentl y these warni ngs are enabl ed by defaul t for backwards
compati bi l i ty reasons. I n future rel eases of MATLAB, the warni ngs wi l l be
di sabl ed by defaul t. The programmer wi l l be responsi bl e for enabl i ng these
warni ngs duri ng the MEX-fi l e devel opment cycl e.
Example That Causes Warning
mxArray *temp = mxCreateDoubleMatrix(1,1,mxREAL);
...
mxFree(temp); /* INCORRECT */
mxFree does not destroy the array object. Thi s operati on frees the structure
header associ ated wi th the array, but MATLAB wi l l sti l l operate as i f the array
object needs to be destroyed. Thus MATLAB wi l l try to destroy the array object,
and i n the process, attempt to free i ts structure header agai n.
Solution
Cal l mxDestroyArray i nstead.
mxDestroyArray(temp); /* CORRECT */
Incorrectly Constructing a Cell or Structure mxArray
You cannot cal l mxSetCell or mxSetField var i ants wi th prhs[] as the member
array.
Warning
Warning: You are attempting to use an array from another scope
(most likely an input argument) as a member of a cell array or
structure. You need to make a copy of the array first. MATLAB will
attempt to fix the problem and continue, but this will result in
memory faults in future releases.
8 System Setup
8-18
Example That Causes Warning
myfunction('hello')
/* myfunction is the name of your MEX-file and your code */
/* contains the following: */
mxArray *temp = mxCreateCellMatrix(1,1);
...
mxSetCell(temp, 0, prhs[0]); /* INCORRECT */
When the MEX-fi l e returns, MATLAB wi l l destroy the enti re cel l array. Si nce
thi s i ncl udes the members of the cel l , thi s wi l l i mpl i ci tl y destroy the MEX-fi l es
i nput arguments. Thi s can cause several strange resul ts, general l y havi ng to
do wi th the corrupti on of the cal l ers workspace, i f the ri ght-hand si de
argument used i s a temporary array (i .e., a l i teral or the resul t of an
expressi on).
Solution
Make a copy of the ri ght-hand si de argument wi th mxDuplicateArray and use
that copy as the argument to mxSetCell (or mxSetField vari ants); for exampl e
mxSetCell(temp, 0, mxDuplicateArray(prhs[0])); /* CORRECT */
Creating a Temporary mxArray with Improper Data
You cannot cal l mxDestroyArray on an mxArray whose data was not al l ocated
by an API routi ne.
Warning
Warning: You have attempted to point the data of an array to a
block of memory not allocated through the MATLAB API. MATLAB will
attempt to fix the problem and continue, but this will result in
memory faults in future releases.
Example That Causes Warning
I f you cal l mxSetPr, mxSetPi, mxSetData, or mxSetImagData wi th memory as the
i ntended data bl ock (second argument) that was not al l ocated by mxCalloc,
mxMalloc, or mxRealloc:
mxArray *temp = mxCreateDoubleMatrix(0,0,mxREAL);
Troubleshooting
8-19
double data[5] = {1,2,3,4,5};
...
mxSetM(temp,1); mxSetN(temp,5); mxSetPr(temp, data);
/* INCORRECT */
then when the MEX-fi l e returns, MATLAB wi l l attempt to free the poi nter to
real data and the poi nter to i magi nary data (i f any). Thus MATLAB wi l l
attempt to free memory, i n thi s exampl e, from the program stack. Thi s wi l l
cause the above warni ng when MATLAB attempts to reconci l e i ts consi stency
checki ng i nformati on.
Solution
Rather than use mxSetPr to set the data poi nter, i nstead create the mxArray
wi th the ri ght si ze and use memcpy to copy the stack data i nto the buffer
returned by mxGetPr.
mxArray *temp = mxCreateDoubleMatrix(1,5,mxREAL);
double data[5] = {1,2,3,4,5};
...
memcpy(mxGetPr(temp), data, 5*sizeof(double)); /* CORRECT */
Potential Memory Leaks
Pri or to Versi on 5.2, i f you created an mxArray usi ng one of the API creati on
routi nes and then you overwrote the poi nter to the data usi ng mxSetPr,
MATLAB woul d sti l l free the ori gi nal memory. Thi s i s no l onger the case.
For exampl e
pr = mxCalloc(5*5, sizeof(double));
... <load data into pr>
plhs[0] = mxCreateDoubleMatrix(5,5,mxREAL);
mxSetPr(plhs[0], pr); /* INCORRECT */
wi l l now l eak 5*5*8 bytes of memory, where 8 bytes i s the si ze of a double.
You can avoi d that memory l eak by changi ng the code
plhs[0] = mxCreateDoubleMatrix(5,5,mxREAL);
pr = mxGetPr(plhs[0]);
... <load data into pr>
8 System Setup
8-20
or al ternati vel y
pr = mxCalloc(5*5, sizeof(double));
... <load data into pr>
plhs[0] = mxCreateDoubleMatrix(5,5,mxREAL);
mxFree(mxGetPr(plhs[0]));
mxSetPr(plhs[0], pr);
Note that the fi rst sol uti on i s more effi ci ent.
Si mi l ar memory l eaks can al so occur when usi ng mxSetPi, mxSetData,
mxSetImagData, mxSetIr, or mxSetJc. You can address thi s i ssue as shown
above to avoi d such memory l eaks.
MEX-Files Should Destroy Their Own Temporary Arrays
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. Al l mxArrays except those returned
i n the l eft-hand si de l i st and those returned by mexGetArrayPtr may be safel y
destroyed. Thi s approach i s consi stent wi th other MATLAB API appl i cati ons
(i .e., MAT-fi l e appl i cati ons, engi ne appl i cati ons, and MATLAB Compi l er
generated appl i cati ons, whi ch do not have any automati c cl eanup mechani sm.)
A
API Functi ons
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
A API Functions
A-2
C MX-Functions
char *mxArrayToString(const mxArray *array_ptr)
void mxAssert(int expr, char *error_message)
void mxAssertS(int expr, char *error_message)
int mxCalcSingleSubscript(const mxArray *array_ptr,
int nsubs, int *subs)
void *mxCalloc(size_t n, size_t size)
void mxClearLogical(mxArray *array_ptr)
typedef enum mxComplexity(mxREAL=0, mxCOMPLEX)
mxArray *mxCreateCellArray(int ndim, const int *dims)
mxArray *mxCreateCellMatrix(int m, int n)
mxArray *mxCreateCharArray(int ndim, const int *dims)
mxArray *mxCreateCharMatrixFromStrings(int m,
const char **str)
mxArray *mxCreateDoubleMatrix(int m, int n,
mxComplexity ComplexFlag)
mxCreateFull (Obsolete)
mxArray *mxCreateNumericArray(int ndim, const int *dims,
mxClassID class, mxComplexity ComplexFlag)
mxArray *mxCreateSparse(int m, int n, int nzmax,
mxComplexity ComplexFlag)
mxArray *mxCreateString(const char *str)
mxArray *mxCreateStructArray(int ndim, const int *dims,
int nfields,const char **field_names)
mxArray *mxCreateStructMatrix(int m, int n, int nfields,
const char **field_names)
void mxDestroyArray(mxArray *array_ptr)
mxArray *mxDuplicateArray(const mxArray *in)
mxArray *mxFree(void *ptr)
mxFreeMatrix (Obsolete)
mxArray *mxGetCell(const mxArray *array_ptr, int index)
mxClassID mxGetClassID(const mxArray *array_ptr)
const char *mxGetClassName(const mxArray *array_ptr)
void *mxGetData(const mxArray *array_ptr)
const int *mxGetDimensions(const mxArray *array_ptr)
int mxGetElementSize(const mxArray *array_ptr)
double mxGetEps(void)
mxArray *mxGetField(const mxArray *array_ptr, int index,
const char *field_name)
A-3
mxArray *mxGetFieldByNumber(const mxArray *array_ptr,
int index, int *field_number)
const char *mxGetFieldNameByNumber(const mxArray *array_ptr,
int field_number)
int mxGetFieldNumber(const mxArray *array_ptr,
const char *field_name)
void *mxGetImagData(const mxArray *array_ptr)
double mxGetInf(void)
int *mxGetIr(const mxArray *array_ptr)
int *mxGetJc(const mxArray *array_ptr)
int mxGetM(const mxArray *array_ptr)
int mxGetN(const mxArray *array_ptr)
const char *mxGetName(const mxArray *array_ptr)
double mxGetNaN(void)
int mxGetNumberOfDimensions(const mxArray *array_ptr)
int mxGetNumberOfElements(const mxArray *array_ptr)
int mxGetNumberOfFields(const mxArray *array_ptr)
int mxGetNzmax(const mxArray *array_ptr)
double *mxGetPi(const mxArray *array_ptr)
double *mxGetPr(const mxArray *array_ptr)
double mxGetScalar(const mxArray *array_ptr)
int mxGetString(const mxArray *array_ptr, char *buf,
int buflen)
bool mxIsCell(const mxArray *array_ptr)
bool mxIsChar(const mxArray *array_ptr)
bool mxIsClass(const mxArray *array_ptr, const char *name)
bool mxIsComplex(const mxArray *array_ptr)
bool mxIsDouble(const mxArray *array_ptr)
bool mxIsEmpty(const mxArray *array_ptr)
bool mxIsFinite(double value)
bool mxIsFromGlobalWS(const mxArray *array_ptr)
mxIsFull (Obsolete)
bool mxIsInf(double value)
bool mxIsInt8(const mxArray *array_ptr)
bool mxIsInt16(const mxArray *array_ptr)
bool mxIsInt32(const mxArray *array_ptr)
bool mxIsLogical(const mxArray *array_ptr)
bool mxIsNaN(double value)
bool mxIsNumeric(const mxArray *array_ptr)
bool mxIsSingle(const mxArray *array_ptr)
A API Functions
A-4
bool mxIsSparse(const mxArray *array_ptr)
mxIsString (Obsolete)
bool mxIsStruct(const mxArray *array_ptr)
bool mxIsUint8(const mxArray *array_ptr)
bool mxIsUint16(const mxArray *array_ptr)
bool mxIsUint32(const mxArray *array_ptr)
void *mxMalloc(size_t n)
void *mxRealloc(void *ptr, size_t size)
void mxSetAllocFcns(calloc_proc callocfcn, free_proc freefcn,
realloc_proc reallocfcn, malloc_proc mallocfcn)
void mxSetCell(mxArray *array_ptr, int index, mxArray *value)
int mxSetClassName(mxArray *array_ptr, const char *classname)
void mxSetData(mxArray *array_ptr, void *data_ptr)
int mxSetDimensions(mxArray *array_ptr, const int *dims,
int ndims)
void mxSetField(mxArray *array_ptr, int index,
const char *field_name, mxArray *value)
void mxSetFieldByNumber(mxArray *array_ptr, int index,
int field_number, mxArray *value)
void mxSetImagData(mxArray *array_ptr, void *pi)
void mxSetIr(mxArray *array_ptr, int *ir)
void mxSetJc(mxArray *array_ptr, int *jc)
void mxSetLogical(mxArray *array_ptr)
void mxSetM(mxArray *array_ptr, int m)
void mxSetN(mxArray *array_ptr, int n)
void mxSetName(mxArray *array_ptr, const char *name)
void mxSetNzmax(mxArray *array_ptr, int nzmax)
void mxSetPi(mxArray *array_ptr, double *pi)
void mxSetPr(mxArray *array_ptr, double *pr)
C MEX-Functions
void mexAddFlops(int count)
int mexAtExit(void (*ExitFcn)(void))
int mexCallMATLAB(int nlhs, mxArray *plhs[], int nrhs,
mxArray *prhs[], const char *command_name)
void mexErrMsgTxt(const char *error_msg)
int mexEvalString(const char *command)
void mexFunction(int nlhs, mxArray *plhs[], int nrhs,
const mxArray *prhs[])
A-5
const char *mexFunctionName(void)
const mxArray *mexGet(double handle, const char *property)
mxArray *mexGetArray(const char *name, const char *workspace)
const mxArray *mexGetArrayPtr(const char *name,
const char *workspace)
mexGetEps (Obsolete)
mexGetFull (Obsolete)
mexGetGlobal (Obsolete)
mexGetInf (Obsolete)
mexGetMatrix (Obsolete)
mexGetMatrixPtr (Obsolete)
mexGetNaN (Obsolete)
mexIsFinite (Obsolete)
bool mexIsGlobal(const mxArray *array_ptr)
mexIsInf (Obsolete)
bool mexIsLocked(void)
mexIsNaN (Obsolete)
void mexLock(void)
void mexMakeArrayPersistent(mxArray *array_ptr)
void mexMakeMemoryPersistent(void *ptr)
int mexPrintf(const char *format, ...)
int mexPutArray(mxArray *array_ptr, const char *workspace)
mexPutFull (Obsolete)
mexPutMatrix (Obsolete)
int mexSet(double handle, const char *property,
mxArray *value)
void mexSetTrapFlag(int trap_flag)
void mexUnlock(void)
void mexWarnMsgTxt(const char *warning_msg)
C MAT-File Routines
int matClose(MATFile *mfp)
int matDeleteArray(MATFile *mfp, const char *name)
matDeleteMatrix (obsolete)
mxArray *matGetArray(MATFile *mfp, const char *name)
mxArray *matGetArrayHeader(MATFile *mfp, const char *name)
char **matGetDir(MATFile *mfp, int *num)
FILE *matGetFp(MATFile *mfp)
matGetFull (obsolete)
A API Functions
A-6
matGetMatrix (obsolete)
mxArray *matGetNextArray(MATFile *mfp)
mxArray *matGetNextArrayHeader(MATFile *mfp)
matGetNextMatrix (Obsolete)
matGetString (Obsolete)
MATFile *matOpen(const char *filename, const char *mode)
int matPutArray(MATFile *mfp, const mxArray *mp)
int matPutArrayAsGlobal(MATFile *mfp, const mxArray *mp)
matPutFull (Obsolete)
matPutMatrix (Obsolete)
matPutString (Obsolete)
C Engine Routines
int engClose(Engine *ep)
int engEvalString(Engine *ep, const char *string)
mxArray *engGetArray(Engine *ep, const char *name)
engGetFull (obsolete)
engGetMatrix (obsolete)
Engine *engOpen(const char *startcmd)
int engOutputBuffer(Engine *ep, char *p, int n)
int engPutArray(Engine *ep, const mxArray *mp)
engPutFull (obsolete)
engPutMatrix (obsolete)
engSetEvalCallback (obsolete)
engSetEvalTimeout (obsolete)
engWinInit (obsolete)
Fortran MX-Functions
integer*4 function mxCalloc(n, size)
subroutine mxCopyCharacterToPtr(y, px, n)
subroutine mxCopyComplex16ToPtr(y, pr, pi, n)
subroutine mxCopyInteger4ToPtr(y, px, n)
subroutine mxCopyPtrToCharacter(px, y, n)
subroutine mxCopyPtrToComplex16(pr, pi, y, n)
subroutine mxCopyPtrToInteger4(px, y, n)
subroutine mxCopyPtrToPtrArray(px, y, n)
subroutine mxCopyPtrToReal8(px, y, n)
subroutine mxCopyReal8ToPtr(y, px, n)
A-7
integer*4 function mxCreateFull(m, n, ComplexFlag)
integer*4 function mxCreateSparse(m, n, nzmax, ComplexFlag)
integer*4 function mxCreateString(str)
subroutine mxFree(ptr)
subroutine mxFreeMatrix(pm)
integer*4 function mxGetIr(pm)
integer*4 function mxGetJc(pm)
integer*4 function mxGetM(pm)
integer*4 function mxGetN(pm)
character*32 function mxGetName(pm)
integer*4 function mxGetNzmax(pm)
integer*4 function mxGetPi(pm)
integer*4 function mxGetPr(pm)
real*8 function mxGetScalar(pm)
integer*4 function mxGetString(pm, str, strlen)
integer*4 function mxIsComplex(pm)
integer*4 function mxIsDouble(pm)
integer*4 function mxIsFull(pm)
integer*4 function mxIsNumeric(pm)
integer*4 function mxIsSparse(pm)
integer*4 function mxIsString(pm)
subroutine mxSetIr(pm, ir)
subroutine mxSetJc(pm, jc)
subroutine mxSetM(pm, m)
subroutine mxSetN(pm, n)
subroutine mxSetName(pm, name)
subroutine mxSetNzmax(pm, nzmax)
subroutine mxSetPi(pm, pi)
subroutine mxSetPr(pm, pr)
Fortran MEX-Functions
integer*4 function mexAtExit(ExitFcn)
integer*4 function mexCallMATLAB(nlhs, plhs, nrhs, prhs, name)
subroutine mexErrMsgTxt(error_msg)
integer*4 function mexEvalString(command)
subroutine mexFunction(nlhs, plhs, nrhs, prhs)
real*8 function mexGetEps()
integer*4 function mexGetFull(name, m, n, pr, pi)
integer*4 function mexGetGlobal(name)
A API Functions
A-8
real*8 function mexGetInf()
integer*4 function mexGetMatrix(name)
integer*4 function mexGetMatrixPtr(name)
real*8 function mexGetNaN()
integer*4 function mexIsFinite(value)
integer*4 function mexIsInf(value)
integer*4 function mexIsNaN(value)
subroutine mexPrintf(message)
integer*4 function mexPutFull(name, m, n, pr, pi)
integer*4 function mexPutMatrix(mp)
subroutine mexSetTrapFlag(trap_flag)
Fortran MAT-File Routines
integer*4 function matClose(mfp)
subroutine matDeleteMatrix(mfp, name)
integer*4 function matGetDir(mfp, num)
integer*4 function matGetFull(mfp, name, m, n, pr, pi)
integer*4 function matGetMatrix(mfp, name)
integer*4 function matGetNextMatrix(mfp)
integer*4 function matGetString(mfp, name, str, strlen)
integer*4 function matOpen(filename, mode)
integer*4 function matPutFull(mfp, name, m, n, pr, pi)
integer*4 function matPutMatrix(mfp, mp)
integer*4 function matPutString(mfp, name, str)
Fortran Engine Routines
integer*4 function engClose(ep)
integer*4 function engEvalString(ep, command)
integer*4 function engGetFull(ep, name, m, n, pr, pi)
integer*4 function engGetMatrix(ep, name)
integer*4 function engOpen(startcmd)
integer*4 function engOutputBuffer(ep, p)
integer*4 function engPutFull(ep, name, m, n, pr, pi)
integer*4 function engPutMatrix(ep, mp)
A-9
DDE Routines
rc = ddeadv(channel, item, callback, upmtx, format, timeout)
rc = ddeexec(channel, command, item, timeout)
channel = ddeinit(service, topic)
rc = ddepoke(channel, item, data, format, timeout)
data = ddereq(channel, item, format, timeout)
rc = ddeterm(channel)
rc = ddeunadv(channel, item, format, timeout)
A API Functions
A-10
B
Di rectory Organi zati on
Directory Organization on UNIX . . . . . . . . . . . B-3
<matl ab>/bi n . . . . . . . . . . . . . . . . . . . . B-4
<matl ab>/extern . . . . . . . . . . . . . . . . . . . B-4
<matl ab>/hel p . . . . . . . . . . . . . . . . . . . . B-6
Directory Organization on Windows . . . . . . . . . B-7
<matl ab>\bi n . . . . . . . . . . . . . . . . . . . . B-8
<matl ab>\extern . . . . . . . . . . . . . . . . . . . B-8
<matl ab>\hel p . . . . . . . . . . . . . . . . . . . B-9
B Directory Organization
B-2
Thi s appendi x descri bes the di rectory organi zati on and purpose of the fi l es
associ ated wi th the MATLAB API on UNI X and Mi crosoft Wi ndows systems.
Directory Organization on UNIX
B-3
Directory Organization on UNIX
Thi s fi gure i l l ustrates the di rectori es i n whi ch the MATLAB API fi l es are
l ocated.
I n the i l l ustrati on, <matlab> symbol i zes the top-l evel di rectory where
MATLAB i s i nstal l ed on your system.
extern
lib
bin
<matlab>
$ARCH
include
src
help
pdf_doc
examples
mex
eng_mat
mx
refbook
support
tech_doc
toolbox
@uint16
B Directory Organization
B-4
<matlab>/bin
The <matlab>/bin di rectory contai ns two fi l es that are rel evant for the
MATLAB API :
mex UNI X shel l scri pt that creates MEX-fi l es from C or
Fortran MEX-fi l e source code. See the Application
ProgramI nterfaceGuidefor more detai l s on mex.
matlab UNI X shel l scri pt that i ni ti al i zes your envi ronment
and then i nvokes the MATLAB i nterpreter.
Thi s di rectory al so contai ns the preconfi gured opti ons fi l es that the mex scri pt
uses wi th parti cul ar compi l ers. Tabl e B-1 l i sts the opti ons fi l es.
<matlab>/extern
<matlab>/extern/lib/$ARCH
The <matlab>/extern/lib/$ARCH di rectory contai ns l i brari es, where $ARCH
speci fi es a parti cul ar UNI X pl atform. For exampl e, on a Sun SPARCstati on
runni ng SunOs 4, the $ARCH di rectory i s named sun4.
On some UNI X pl atforms, thi s di rectory contai ns two versi ons of thi s l i brary.
Li brary fi l enames endi ng wi th .a are stati c l i brari es and fi l enames endi ng
wi th .so or .sl are shared l i brari es.
<matlab>/extern/include
The <matlab>/extern/include di rectory contai ns the header fi l es for
devel opi ng C and C++ appl i cati ons that i nterface wi th MATLAB.
The rel evant header fi l es for the MATLAB API are:
engine.h Header fi l e for MATLAB engi ne programs. Contai ns
functi on prototypes for engi ne routi nes.
Table B-1: Preconfigured Options Files
mexopts.sh System ANSI Compi l er
gccopts.sh GCC (GNU C Compi l er)
cxxopts.sh System C++ Compi l er
Directory Organization on UNIX
B-5
mat.h Header fi l e for programs accessi ng MAT-fi l es.
Contai ns functi on prototypes for mat routi nes.
matrix.h Header fi l e contai ni ng a defi ni ti on of the mxArray
structure and functi on prototypes for matri x access
routi nes.
mex.h Header fi l e for bui l di ng MEX-fi l es. Contai ns functi on
prototypes for mex routi nes.
<matlab>/extern/src
The <matlab>/extern/src di rectory contai ns those C source fi l es that are
necessary to support certai n MEX-fi l e features such as argument checki ng and
versi oni ng.
<matlab>/extern/examples/eng_mat
The <matlab>/extern/examples/eng_mat di rectory contai ns exampl es for
usi ng the MATLAB engi ne faci l i ty, as wel l as exampl es for readi ng and wri ti ng
MATLAB data fi l es (MAT-fi l es). These exampl es are al l stand-al one programs.
<matlab>/extern/examples/mex
The <matlab>/extern/examples/mex di rectory contai ns MEX-fi l e exampl es. I t
i ncl udes the exampl es descri bed i n the onl i ne API reference pages for MEX
i nterface functi ons (the functi ons begi nni ng wi th the mex prefi x).
<matlab>/extern/examples/mx
The <matlab>/extern/examples/mx di rectory contai ns exampl es for usi ng the
array access functi ons. Al though you can use these functi ons i n stand-al one
programs, most of these are MEX-fi l e exampl es. The excepti on i s
mxSetAllocFcns.c, si nce thi s functi on i s avai l abl e onl y to stand-al one
programs.
<matlab>/extern/examples/refbook
The <matlab>/extern/examples/refbook di rectory contai ns the exampl es
that are di scussed i n the Application ProgramI nterfaceGuide.
B Directory Organization
B-6
<matlab>/extern/examples/refbook/@uint16
The <matlab>/extern/examples/refbook/@uint16 di rectory contai ns the EQ
and NEQ over l oaded functi ons.
<matlab>/help
<matlab>/help/pdf_doc
The <matlab>/help/pdf_doc di rectory contai ns onl i ne hel p fi l es for MATLAB
and other tool boxes i n PDF format.
<matlab>/help/support
The <matlab>/help/support di rectory contai ns a Worl d Wi de Web l i nk to the
MathWorks Techni cal Support Departments troubl eshooti ng tool s such as:
Sol uti on Search Engi ne
FAQ (Frequentl y Asked Questi ons)
Techni cal Notes
<matlab>/help/tech_doc
The <matlab>/help/techdoc di rectory contai ns addi ti onal techni cal
documentati on for MATLAB i n HTML format, vi ewabl e through the MATLAB
Hel p Desk.
<matlab>/help/toolbox
The <matlab>/help/toolbox di rectory contai ns onl i ne hel p documentati on for
MATLAB and other tool boxes i n HTML format, vi ewabl e through the
MATLAB Hel p Desk.
Table B-2: Overloaded Functions
EQ EQ overl oaded functi on equal for uint16 type
NEQ NEQ overl oaded functi on not equal for uint16 type
Directory Organization on Windows
B-7
Directory Organization on Windows
Thi s fi gure i l l ustrates the di rectori es i n whi ch the MATLAB API fi l es are
l ocated.
I n the i l l ustrati on, <matlab> symbol i zes the top-l evel di rectory where
MATLAB i s i nstal l ed on your system.
extern
bin
<matlab>
include
src
help
pdf_doc
support
examples
mex
eng_mat
mx
refbook
techdoc
toolbox
B Directory Organization
B-8
<matlab>\bin
The <matlab>\bin di rectory contai ns the mex.bat batch fi l e that bui l ds C and
Fortran fi l es i nto MEX-fi l es. Thi s di rectory al so contai ns the preconfi gured
opti ons fi l es that the mex scri pt uses wi th parti cul ar compi l ers. See Tabl e 2-2
i n Chapter 2 for a compl ete l i st of the opti ons fi l es.
<matlab>\extern
<matlab>\extern\include
The <matlab>\extern\include di rectory contai ns the header fi l es for
devel opi ng C and C++ appl i cati ons that i nterface wi th MATLAB.
The rel evant header fi l es for the MATLAB API (MEX-fi l es, engi ne, and
MAT-fi l es) are:
engine.h Header fi l e for MATLAB engi ne programs. Contai ns
functi on prototypes for engi ne routi nes.
mat.h Header fi l e for programs accessi ng MAT-fi l es.
Contai ns functi on prototypes for mat routi nes.
matrix.h Header fi l e contai ni ng a defi ni ti on of the mxArray
structure and functi on prototypes for matri x access
routi nes.
mex.h Header fi l e for bui l di ng MEX-fi l es. Contai ns functi on
prototypes for mex routi nes.
_*.def Fi l es used by Borl and compi l er.
*.def Fi l es used by MSVC and Mi crosoft Fortran compi l ers.
mexversion.rc Resource fi l e for i nserti ng versi oni ng i nformati on i nto
MEX-fi l es.
<matlab>\extern\src
The <matlab>\extern\src di rectory contai ns fi l es that are used for debuggi ng
MEX-fi l es.
<matlab>\extern\examples\eng_mat
The <matlab>\extern\examples\eng_mat di rectory contai ns exampl es for
usi ng the MATLAB engi ne faci l i ty, as wel l as exampl es for readi ng and wri ti ng
MATLAB data fi l es (MAT-fi l es). These exampl es are al l stand-al one programs.
Directory Organization on Windows
B-9
<matlab>\extern\examples\mex
The <matlab>\extern\examples\mex di rectory contai ns MEX-fi l e exampl es. I t
i ncl udes the exampl es descri bed i n the onl i ne API reference pages for MEX
i nterface functi ons (the functi ons begi nni ng wi th the mex prefi x).
<matlab>\extern\examples\mx
The <matlab>\extern\examples\mx di rectory contai ns exampl es for usi ng the
array access functi ons. Al though you can use these functi ons i n stand-al one
programs, most of these are MEX-fi l e exampl es. The excepti on i s
mxSetAllocFcns.c, si nce thi s functi on i s avai l abl e onl y to stand-al one
programs.
<matlab>\extern\examples\refbook
The <matlab>\extern\examples\refbook di rectory contai ns the exampl es
that are di scussed i n the Application ProgramI nterfaceGuide.
<matlab>\help
<matlab>\help\pdf_doc
The <matlab>\help\pdf_doc di rectory contai ns onl i ne hel p fi l es for MATLAB
and other tool boxes i n PDF format.
<matlab>\help\support
The <matlab>\help\support di rectory contai ns a Worl d Wi de Web l i nk to the
MathWorks Techni cal Support Departments troubl eshooti ng tool s such as:
Sol uti on Search Engi ne
FAQ (Frequentl y Asked Questi ons)
Techni cal Notes
<matlab>\help\techdoc
The <matlab>\help\techdoc di rectory contai ns addi ti onal techni cal
documentati on for MATLAB i n HTML format, vi ewabl e through the MATLAB
Hel p Desk.
B Directory Organization
B-10
<matlab>\help\toolbox
The <matlab>\help\toolbox di rectory contai ns onl i ne hel p documentati on for
MATLAB and other tool boxes i n HTML format, vi ewabl e through the
MATLAB Hel p Desk.
I-1
Index
Symbols
%val 4-5, 4-8
al l ocati ng memory 4-26
DI GI TAL Vi sual For tran 4-8
A
Acti veX 6-4, 7-2, 7-26
actxcontrol 7-6
actxserver 7-10
automati on cl i ent 7-3
automati on server 7-3
cal l back 7-21
col l ecti ons 7-23
COM. SeeCOM (Component Object Model ).
concepts 7-2
control contai nment 7-3
control l er 7-26
Count property 7-23
delete 7-20
event 7-2
event handl er functi on 7-21
get 7-15
i nterface 7-2
custom 7-3
standard 7-3
invoke 7-12
i nvoki ng event 7-21
Item method 7-23
l aunchi ng server 7-30
l i mi tati ons of MATLAB support 7-26
method 7-2, 7-27
object 7-2, 7-23
ProgI D 7-4
propedit 7-17
property 7-2
release 7-18
server 7-26
set 7-14
acti vex 7-4
actxcontrol 7-6
actxserver 7-10
API
access methods 2-3
documentati on 1-8
exampl es 1-8
memory management 8-16
supported functi onal i ty 1-2
argcheck opti on 8-2
argument checki ng 3-9
array
cel l 1-6
empty 1-7
hybri d 3-40
l ogi cal 1-6
MATLAB 1-4
mul ti di mensi onal 1-6
persi stent 3-38
sparse 3-29
temporary 3-38, 4-37
array access methods 4-7
mat 5-2
ASCI I fi l e mode 5-4
ASCI I fl at fi l e 5-3
automati on
control l er 7-26
server 7-27
B
bccengmatopts.bat 2-9
bccopts.bat 2-9
bi nary fi l e mode 5-4
Index
I-2
BSTR 7-27
C
C exampl e
convec.c 3-21
doubleelem.c 3-24
findnz.c 3-26
fulltosparse.c 3-30
phonebook.c 3-17
revord.c 3-11
sincall.c 3-33
timestwo.c 3-8
timestwoalt.c 3-10
xtimesy.c 3-14
C l anguage
data types 1-7
debuggi ng 3-41
MEX-fi l es 3-2
C l anguage exampl e
basi c 3-8
cal l i ng MATLAB functi ons 3-33
cal l i ng user-defi ned functi ons 3-33
handl i ng 8-, 16-, 32-bi t data 3-23
handl i ng arr ays 3-25
handl i ng compl ex data 3-20
handl i ng sparse arrays 3-29
passi ng mul ti pl e val ues 3-14
persi stent arr ay 3-39
stri ngs 3-11
c opti on 8-2
cal l back 7-21
cal l er workspace 3-37
cel l 1-6
cell 1-7
cel l array 1-6
cel l arrays 3-16
char 1-7
cl i ent (DDE) 7-32
col l ecti ons 7-23
COM (Component Object Model ) 7-2
object model 7-3
commands. Seei ndi vi dual commands.
compi l er
debuggi ng
DI GI TAL Vi sual Fortran 4-39
Mi crosoft 3-42
Watcom 3-43
pr econfi gured opti ons fi l e 2-9-2-10
sel ecti ng on Wi ndows 2-6
compi l i ng
engi ne appl i cati on
UNI X 6-16-6-17
Wi ndows 6-18
MAT-fi l e appl i cati on
UNI X 5-29
Wi ndows 5-31
compl ex data
i n Fortran 4-22
computati onal routi ne 3-2, 4-2
confi gurati on 2-5
pr obl ems 8-13
testi ng 2-4
troubl eshooti ng 2-12
UNI X 2-5
Wi ndows 2-6, 2-7
convec.c 3-21
convec.f 4-23
conversati on (DDE) 7-32
Count property 7-23
cxxopts.sh 2-10
Index
I-3
D
D opti on 8-2
data 1-4
MATLAB
exporti ng from 5-3-5-4
i mporti ng to 5-2-5-3
data storage 1-4
data type 3-7
C l anguage 1-7
cel l array 1-6
checki ng 3-9
compl ex doubl e-preci si on nonsparse matri x
1-5
empty array 1-7
For tran 4-2
For tran l anguage 1-7
l ogi cal array 1-6
MAT-fi l e 5-5
MATLAB 1-7
MATLAB stri ng 1-5
mul ti di mensi onal array 1-6
numeri c matri x 1-5
object 1-6
sparse matri x 1-5
structure 1-6
dblmat.f 4-26
dbmex 3-41, 4-38
DCOM (di stri buted component object model )
7-31
usi ng MATLAB as a server 7-31
DDE 7-32
accessi ng MATLAB as server 7-34
advi sory l i nks 7-41
cl i ent 7-32
conversati on 7-32
functi ons A-9
hot l i nk 7-41
i tem 7-33
MATLAB
requesti ng data from 7-36
sendi ng commands to 7-36
sendi ng data to 7-37
usi ng as cl i ent 7-39
name hi erarchy 7-35
noti fyi ng when data changes 7-41
server 7-32
servi ce name 7-33
topi c 7-33, 7-35-7-39
engi ne 7-35
system 7-35
war m l i nk 7-41
Wi ndows cl i pboard formats 7-33-7-34
ddeadv 7-40
ddeexec 7-40
ddeinit 7-40
ddepoke 7-40
ddereq 7-40
ddeterm 7-40
ddeunadv 7-40
debuggi ng C l anguage MEX-fi l es 3-41
UNI X 3-41
Wi ndows 3-42
debuggi ng Fortran l anguage MEX-fi l es
UNI X 4-38
Wi ndows 4-39
DEC Al pha
decl ari ng poi nters 4-5
delete 7-20
df50engmatopts.bat 2-9
df50opts.bat 2-9
diary 5-3
di ary fi l e 5-3
DI GI TAL Vi sual Fortran compi l er
debuggi ng 4-39
Index
I-4
di rectory
eng_mat 1-8
mex 1-8
mx 1-8
refbook 1-8
di rectory organi zati on
C l anguage MEX-fi l e 3-2
Fortran l anguage MEX-fi l e 4-2
MAT-fi l e appl i cati on 5-7
Mi crosoft Wi ndows B-7
opti ons fi l e 2-10, 8-4
UNI X B-3
di rectory path
conventi on 2-5
di stri buted component object model . See
DCOM.
dll extensi on 2-2
DLLs 2-4
l ocati ng 2-12
documentati on 1-8
organi zati on 1-9
PDF versi ons 1-8
documenti ng MEX-fi l e 3-37, 4-36
double 1-7
doubleelem.c 3-24
dynami c data exchange. SeeDDE.
dynami c memory al l ocati on
i n Fortran 4-26
mxCalloc 3-11
dynami cal l y l i nked subr outi ne 1-2, 2-2
E
empty array 1-7
eng_mat di rectory 1-8, 6-5
engClose 6-3
engdemo.c 6-5
engEvalString 6-3
engGetArray 6-3
engGetMatrix 6-3
engi ne
compi l i ng 6-14
l i nki ng 6-14
overvi ew 1-3
UNI X 6-16
Wi ndows 6-18
engi ne exampl e
cal l i ng MATLAB
fr om C program 6-5
fr om Fortran pr ogram 6-10
engi ne functi ons 6-3
C l anguage A-6
For tran l anguage A-8
engi ne l i brary 6-2
communi cati ng wi th MATLAB
UNI X 6-4
Wi ndows 6-4
engOpen 6-3
engOutputBuffer 6-3
engPutArray 6-3
engPutMatrix 6-3
engwindemo.c 5-18, 6-5
event handl er
wri ti ng 7-21
event handl er functi on 7-21
exampl e fi l es 1-8
examples di rectory 1-8
excepti on
fl oati ng-poi nt 5-28, 6-14
Execute method 7-27
explore exampl e 1-7
extensi on
MEX-fi l e 2-2
Index
I-5
F
F opti on 8-3
f opti on 2-8, 8-2
fengdemo.f 6-10
fi l e mode
ASCI I 5-4
bi nary 5-4
fi l es
fl at 5-3
l i nki ng mul ti pl e 3-37, 4-36
sampl e 1-8
findnz.c 3-26
fl oati ng-poi nt excepti ons
Absoft Fortran Compi l er on Li nux 5-29, 6-15
Borl and C++ Compi l er on Wi ndows 5-29, 6-15
DEC Al pha 5-29, 6-15
engi ne appl i cati ons 6-14
maski ng 5-28, 6-14
MAT-fi l e appl i cati ons 5-28
fopen 5-3, 5-4
For tran
case i n 4-6
data types 1-7, 4-2
poi nters
concept 4-5, 4-17
decl ari ng 4-5
For tran exampl e
convec.f 4-23
dblmat.f 4-26
fulltosparse.f 4-29
matsq.f 4-17
passstr.f 4-15
revord.f 4-12
sincall.f 4-32
timestwo.f 4-9
xtimesy.f 4-20
Fortran l anguage exampl e
cal l i ng MATLAB functi ons 4-32
handl i ng compl ex data 4-22
handl i ng sparse matri ces 4-28
passi ng arrays of stri ngs 4-14
passi ng matri ces 4-17
passi ng mul ti pl e val ues 4-19
passi ng scal ar 4-9
passi ng stri ngs 4-12
Fortran l anguage MEX-fi l es 4-2
components 4-2
fortran opti on 4-36
fread 5-3
FTP server 1-9
fulltosparse.c 3-30
fulltosparse.f 4-29
fwrite 5-4
G
g opti on 3-41, 8-3
gateway routi ne 3-2, 4-2, 4-6
accessi ng mxArray data 3-2
gccopts.sh 2-10
get 7-15
GetFullMatrix 7-28
H
h opti on 8-3
help 3-37, 4-36
Hel p Desk 1-8
hel p fi l es 3-37, 4-36
hybri d array 3-40
persi stent 3-40
temporary 3-40
Index
I-6
I
I opti on 8-3
I DE
bui l di ng MEX-fi l es 8-2
I EEE routi nes 2-3
include di rectory 5-7
invoke 7-12
ir 1-5, 3-29, 4-28
Item method 7-23
J
jc 1-5, 3-29, 4-28
L
L opti on 8-3
l i br ary path
setti ng on UNI X 5-29, 6-16
l i nki ng DLLs to MEX-fi l es 8-9
l i nki ng mul ti pl e fi l es 3-37, 4-36
load 5-3, 5-4
l ocati ng DLLs 2-12
l ogi cal ar ray 1-6
M
mat.h 5-7
matClose 5-5, 5-6
matcreat.c 5-10
matDeleteArray 5-5
matDeleteMatrix 5-6
matdemo1.f 5-14
matdemo2.f 5-24
MAT-fi l e
C l anguage
creati ng 5-10
readi ng 5-19
compi l i ng 5-28
data types 5-5
exampl es 5-9
For tran l anguage
creati ng 5-14
readi ng 5-24
l i nki ng 5-28
overvi ew 1-2
subrouti nes 5-5
UNI X l i brari es 5-8
usi ng 5-2
Wi ndows l i brari es 5-8
MAT-fi l e appl i cati on
UNI X 5-29
Wi ndows 5-31
MAT-fi l e exampl e
creati ng
C l anguage 5-10
For tran l anguage 5-14
readi ng
C l anguage 5-19
For tran l anguage 5-24
MAT-fi l e functi ons
C l anguage A-5-A-6
For tran l anguage A-8
MAT-functi ons 5-5-5-6
matGetArray 5-5
matGetArrayHeader 5-6
matGetDir 5-5, 5-6
matGetFp 5-5
matGetMatrix 5-6
matGetNextArray 5-5
matGetNextArrayHeader 5-6
matGetNextMatrix 5-6
Index
I-7
matGetString 5-6
MATLAB
Acti veX i nterface 7-23
array 1-4
as DCOM server cl i ent 7-25
data 1-4
data fi l e format 5-2
data storage 1-4
data type 1-7
engi ne 6-2
exporti ng data 5-2-5-4
Hel p Desk 1-8
i mporti ng data 5-2-5-3
MAT-fi l e 5-4
readi ng arrays from 5-5
savi ng arrays to 5-4
movi ng data between pl atforms 5-4
stand-al one appl i cati ons 1-2, 5-2
stri ng 1-5
usi ng as a computati on engi ne 6-2
vari abl es 1-4
MATLAB Automati on Server
suppor ted methods 7-27
matOpen 5-5, 5-6
matPutArray 5-5
matPutArrayAsGlobal 5-6
matPutMatrix 5-6
matPutString 5-6
matri x
compl ex doubl e-preci si on nonsparse 1-5
numeri c 1-5
sparse 1-5, 4-28
matrix.h 5-7
matsq.f 4-17
memory
al l ocati on 3-11
l eak 3-38, 8-19
temporary 4-37
memory management 3-38, 4-37, 8-16
API 8-16
compati bi l i ty 8-16
routi nes 2-3
speci al consi derati ons 3-38
method
Acti veX 7-27
BSTR 7-28
Execute 7-27
mex
argcheck 8-2
c 8-2
D 8-2
F 8-3
f 8-2
fortran 4-36
g 3-41, 4-38, 8-3
h 8-3
I 8-3
L 8-3
n 8-3
O 8-3
output 8-3
setup 8-4
U 8-4
v 8-4
V4 8-4
mex di rectory 1-8
mex opti ons 8-2
mex scri pt 3-9, 8-2
searchi ng for opti ons fi l e 8-4
swi tches 8-2
mex setup
Wi ndows 2-6
mex.bat 3-9
mex.m 3-9
Index
I-8
mex.sh 3-9
mex4 extensi on 2-2
mexAtExit 3-39
regi ster a functi on 3-39
mexaxp extensi on 2-2
mexCallMATLAB 3-33, 3-36, 3-38, 4-32, 4-34,
4-35
mexErrMsgTxt 3-38, 4-7
mexEvalString 3-37, 4-36
MEX-fi l e 2-2
advanced topi cs 3-37
Fortran 4-36
arguments 3-5
C l anguage 3-2
cal l i ng 2-2
compi l i ng 3-9
Mi crosoft Vi sual C++ 8-9
UNI X 2-5, 8-5-8-7
Wi ndows 2-7, 8-7-8-10
components 3-2
computati on error 8-15
confi gurati on probl em 8-13
creati ng C l anguage 3-2, 3-9
creati ng Fortran l anguage 4-2
custom bui l di ng 8-2
debuggi ng C l anguage 3-41
debuggi ng Fortran l anguage 4-38
DLL l i nki ng 8-9
documenti ng 3-37, 4-36
dynami cal l y al l ocated memory 3-38
exampl es 3-7
extensi ons 2-2
l oad error 8-13
overvi ew 1-2
passi ng cel l ar rays 3-16
passi ng str uctures 3-16
probl em on SGI systems 8-16
pr obl ems 8-12-8-15
segmentati on error 8-14
syntax err ors 8-13
temporary arr ay 3-38
use of 1-2
usi ng 2-2
versi oni ng 8-9
mexFunction 3-2, 4-2, 4-6
al tered name 4-39
par ameters 3-2, 4-2
MEX-functi ons
C l anguage A-4-A-5
For tran l anguage A-7-A-8
mexGetArray 3-37
mexGetMatrix 4-36
mexhp7 extensi on 2-2
mexlx extensi on 2-2
mexMakeArrayPersistent 3-38
mexMakeMemoryPersistent 3-38
mexopts.sh 2-10
mexPutArray 3-37
mexPutMatrix 4-36
mexrs6 extensi on 2-2
mexSetTrapFlag 3-38
mexsg extensi on 2-2
mexsg64 extensi on 2-2
mexsol extensi on 2-2
mexversion.rc 8-9
M-fi l e
creati ng data 5-2
Mi crosoft compi l er
debuggi ng 3-42
Mi crosoft Wi ndows
di r ectory organi zati on B-7
msvc50engmatopts.bat 2-9
msvc50opts.bat 2-9
msvcengmatopts.bat 2-9
Index
I-9
msvcopts.bat 2-9
mul ti di mensi onal array 1-6
mx di rectory 1-8
mxArray 1-4, 4-7
accessi ng data 3-2
contents 1-4
i mproper l y destroyi ng 8-16
ir 1-5
jc 1-5
nzmax 1-5
pi 1-5
pr 1-5
temporary wi th i mproper data 8-18
type 1-4
mxCalloc 3-11, 3-38, 4-7
mxCopyComplex16ToPtr 4-22
mxCopyPtrToComplex16 4-22
mxCopyPtrToReal8 4-8, 4-19
mxCreateFull 4-7, 4-17
mxCreateNumericArray 3-23
mxCreateSparse 4-7
mxCreateString 3-13, 4-7
mxDestroyArray 3-40, 4-37, 8-16
mxFree 8-16
MX-functi ons
C l anguage A-2-A-4
For tran l anguage A-6-A-7
mxGetCell 3-16
mxGetData 3-17, 3-23, 3-26
mxGetField 3-16
mxGetImagData 3-23, 3-26
mxGetPi 3-20, 4-17
mxGetPr 3-16, 3-20, 4-17
mxGetScalar 3-9, 3-16
mxMalloc 3-11, 3-38
mxRealloc 3-11, 3-38
mxSetCell 3-40, 8-17
mxSetData 3-40, 8-18, 8-20
mxSetField 8-17
mxSetImagData 8-18, 8-20
mxSetIr 8-20
mxSetJc 8-20
mxSetPi 8-18, 8-20
mxSetPr 3-40, 8-18, 8-19
mxUNKNOWN_CLASS 3-36, 4-35
N
n opti on 8-3
nlhs 3-2, 3-5, 4-3, 4-6
nrhs 3-2, 3-5, 4-2, 4-6
numer i c matri x 1-5
nzmax 1-5, 4-28
O
O opti on 8-3
object 1-6
opti ons fi l e 2-4
creati ng new 8-2
di rectory or gani zati on 2-10
modi fyi ng 8-4
preconfi gured 2-9
speci fyi ng 2-8
usi ng on UNI X 2-10
usi ng on Wi ndows 2-10
when to speci fy 2-8
output opti on 8-3
P
passstr.f 4-15
persi stent array
exempti ng form cl eanup 3-38
Index
I-10
phonebook.c 3-17
pi 1-5
plhs 3-2, 3-5, 4-2, 4-6
poi nter 4-5
Fortran l anguage MEX-fi l e 4-17
pr 1-5
prhs 3-2, 3-5, 4-2, 4-6
propedit 7-17
protocol
DCOM 7-31
PutFullMatrix 7-29
R
refbook di rectory 1-8
release 7-18
revord.c 3-11
revord.f 4-12
routi ne
computati onal 3-2
gateway 3-2, 4-2
mex 2-3
mx 2-3
S
save 5-3, 5-4
servi ce name 7-32, 7-33
set 7-14
setup opti on 2-6, 8-4
SGI
decl ari ng poi nters on 64-bi t machi nes 4-5
shared l i br ari es di rectory
UNI X 5-8
Wi ndows 5-8
sincall.c 3-33
sincall.f 4-32
so_locations fi l e on SGI 8-16
Sol uti ons Search Engi ne 8-11
sparse 1-7
sparse arr ay 3-29
sparse matr i x 1-5
stori ng data 1-4
str i ng 1-5
struct 1-7
str ucture 1-6, 3-16
subrouti ne
dynami cal l y l i nked 1-2, 2-2
system confi gur ati on 2-5
T
temporary arr ay 3-38
automati c cl eanup 3-38
destr oyi ng 8-20
temporary memory
cl eani ng up 8-20
timestwo.c 3-8
timestwo.f 4-9
timestwoalt.c 3-10
troubl eshooti ng
confi gurati on 2-12
MEX-fi l e creati on 8-11
U
U opti on 8-4
uint8 1-7
UNI X
di r ectory organi zati on B-3
usi ng MEX-fi l es 2-2
Index
I-11
V
v opti on 8-4
V4 opti on 8-4
vari abl e scope 3-37
vari abl es 1-4
versi oni ng MEX-fi l es 8-9
Vi sual Basi c
MATLAB DDE server exampl e 7-38
W
wat11copts.bat 2-9
wat11engmatopts.bat 2-9
Watcom compi l er
debuggi ng 3-43
watcopts.bat 2-9
watengmatopts.bat 2-9
Wi ndows
Acti veX 7-26
automati on 7-26
di r ectory organi zati on B-7
mex setup 2-6
sel ecti ng compi l er 2-6
Wi ndows cl i pboard format
Metafi l epi ct 7-34
text 7-33
XLTabl e 7-34
workspace
cal l er 3-37, 4-36
MEX-fi l e functi on 3-37, 4-36
wri ti ng event handl ers 7-21
X
xtimesy.c 3-14
xtimesy.f 4-20
Y
yprime.c 2-4
yprimef.F 2-4
yprimef.f 2-4
yprimefg.F 2-4
yprimefg.f 2-4