Matlab External interfaces

Similar documents
The aim of this unit is to show other possibilities of MATLAB. There are no Exercises associated with this unit.

MATLAB Compiler 4 User s Guide

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

Designing and Implementing a Java-based GUI for Automatic Generation of MATLAB Gateway Functions of Numerical Subroutines

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

MATLAB/Simulink TCP/IP Communication

MATLAB Functions. function [Out_1,Out_2,,Out_N] = function_name(in_1,in_2,,in_m)

Beginner s Matlab Tutorial

MATLAB Tutorial. Chapter 6. Writing and calling functions

An Incomplete C++ Primer. University of Wyoming MA 5310

Ensure that the AMD APP SDK Samples package has been installed before proceeding.

The programming language C. sws1 1

MatrixSSL Porting Guide

Documentation Installation of the PDR code

Introduction to Linux and Cluster Basics for the CCR General Computing Cluster

MATLAB DFS. Interface Library. User Guide

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint)

Image Acquisition Toolbox Adaptor Kit User's Guide

The C Programming Language course syllabus associate level

Task CMU Report 06: Programs for Design Analysis Support and Simulation Integration. Department of Energy Award # EE

SmartArrays and Java Frequently Asked Questions

Freescale Semiconductor, I

Introduction to Matlab

Matrix Multiplication

How to Use Rohde & Schwarz Instruments in MATLAB Application Note

Athena Knowledge Base

How to use PDFlib products with PHP

How To Use The C Preprocessor

Introduction. Why (GIS) Programming? Streamline routine/repetitive procedures Implement new algorithms Customize user applications

Sources: On the Web: Slides will be available on:

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Compiler Construction

CPLEX Tutorial Handout

Brian Caffo. Using.Call in R

MatrixSSL Developer s Guide

MatrixSSL Getting Started

Xeon Phi Application Development on Windows OS

CS222: Systems Programming

5 Arrays and Pointers

Interactive Applications in Teaching with the MATLAB Web Server. 1 Aim and structure of the MATLAB Web Server

Building Applications Using Micro Focus COBOL

Building Programs with Make. What does it mean to Build a Program?

Product Information CANape Option Simulink XCP Server

SimbaEngine SDK 9.4. Build a C++ ODBC Driver for SQL-Based Data Sources in 5 Days. Last Revised: October Simba Technologies Inc.

Chapter 1: Getting Started

GPU Tools Sandra Wienke

Computational Mathematics with Python

How To Write Portable Programs In C

Topics. Introduction. Java History CS 146. Introduction to Programming and Algorithms Module 1. Module Objectives

1 Topic. 2 Scilab. 2.1 What is Scilab?

Lecture 11 Doubly Linked Lists & Array of Linked Lists. Doubly Linked Lists

Parameter Passing. Parameter Passing. Parameter Passing Modes in Fortran. Parameter Passing Modes in C

How to Write a Simple Makefile

How to test and debug an ASP.NET application

Supported platforms & compilers Required software Where to download the packages Geant4 toolkit installation (release 9.6)

FreeForm Designer. Phone: Fax: POB 8792, Natanya, Israel Document2

Overview. Lecture 1: an introduction to CUDA. Hardware view. Hardware view. hardware view software view CUDA programming

6.s096. Introduction to C and C++

Program 5 - Processes and Signals (100 points)

CE 504 Computational Hydrology Computational Environments and Tools Fritz R. Fiedler

CS1112 Spring 2014 Project 4. Objectives. 3 Pixelation for Identity Protection. due Thursday, 3/27, at 11pm

Data Analysis with MATLAB The MathWorks, Inc. 1

INTEL PARALLEL STUDIO XE EVALUATION GUIDE

Computational Mathematics with Python

How To Create A C++ Web Service

Memory management. Announcements. Safe user input. Function pointers. Uses of function pointers. Function pointer example

Computational Mathematics with Python

Simple File Input & Output

C++ Programming Language

User Manual. 3-Heights PDF Producer API. Version 4.6

JMulTi/JStatCom - A Data Analysis Toolkit for End-users and Developers

Getting Started Guide

Virtuozzo Virtualization SDK

How To Write A Cg Toolkit Program

CPSC 226 Lab Nine Fall 2015

Main Bullet #1 Main Bullet #2 Main Bullet #3

Cincom Smalltalk. Installation Guide P SIMPLIFICATION THROUGH INNOVATION

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Build standalone executables from MATLAB code

Introduction to Programming System Design. CSCI 455x (4 Units)

Application Development Guide: Building and Running Applications

Project Adding a System Call to the Linux Kernel

SQLITE C/C++ TUTORIAL

Introduction to MATLAB Gergely Somlay Application Engineer

2+2 Just type and press enter and the answer comes up ans = 4

AMD CodeXL 1.7 GA Release Notes

Keil C51 Cross Compiler

C++ INTERVIEW QUESTIONS

FIRST STEPS WITH SCILAB

1 Abstract Data Types Information Hiding

Tutorial 5: Developing Java applications

Lecture 1: Systems of Linear Equations

eggon SDK for ios 7 Integration Instructions

OPERATING SYSTEM SERVICES

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Simple C Programs. Goals for this Lecture. Help you learn about:

Expedite for Windows Software Development Kit Programming Guide

GIVE WINGS TO YOUR IDEAS TOOLS MANUAL

Apache Thrift and Ruby

BarTender s ActiveX Automation Interface. The World's Leading Software for Label, Barcode, RFID & Card Printing

Transcription:

Outline Matlab External interfaces Stefan Johansson External interfaces MEX-files Some about Java Component Object Model (COM) Matlab Compiler Department of Computing Science Umeå University Modeling and Simulation: Matlab 2 External interfaces Possible to call and use external software and libraries in Matlab Programs/routines written in C C++ Fortran Java (built-in support) Must be compiled into a binary MEX-file Why call external routines Faster execution Can use and exchange information with existing software and libraries Do not need to rewrite them as m-files Can use external GUIs, e.g. written in Java or Visual Basic Modeling and Simulation: Matlab 3 Modeling and Simulation: Matlab 4

External interfaces MEX-files Shared libraries.dll (Windows).so (UNIX and LINUX) Only Windows COM (Component Object Model) Microsoft.NET Framework Can be accessed directly from Matlab (without any need of a gateway routine) Modeling and Simulation: Matlab 5 External C and Fortran routines compiled for Matlab are called MEX-files MEX-file extensions MS Windows.mexw32 /.mexw64 (from Matlab v. 7.1).dll (until Matlab v. 7.0.4) LINUX.mexglx /.mexa64 Sun Solaris.mexsol /.mexs64 Modeling and Simulation: Matlab 6 MEX-files C compiler for Windows included (LCC) Matlab has support for several external compilers (e.g., MS Visual Studio) External C compiler required for LINUX and UNIX (e.g., gcc) External Fortran compiler required (e.g., gfortran and Intel Fortran) Integrating C files with Matlab A gateway routine is needed as an interface between the computational routine(s) and Matlab The gateway routine must be called mexfunction (compare with the main function) Use the mex command to compile the computational routine(s) together with the gateway routine into a binary MEX-file mex can both be called within Matlab and from the Windows/Linux command prompt Modeling and Simulation: Matlab 7 Modeling and Simulation: Matlab 8

The MEX-file Computational and gateway routines can be in separate files The first file supplied to the mex command must include the gateway routine The name of the binary MEX-file is the name of the function called from Matlab C MEX-file example Compile the C MEX-file (in Matlab or DOS/UNIX command prompt) > mex myfunc.c Call the MEX-file function as a regular Matlab function > val = myfunc(a) Must include a gateway routine for myfunc myfunc.c #include mex.h /*Do the actual computation*/ double dothework(double *A) {... void mexfunction(int nlhs, mxarray *plhs[], int nrhs, const mxarray *prhs[]) {... Obligatory header file Computational routine /* Call the C function */ out = dothework(pa);... Modeling and Simulation: Matlab 9 Modeling and Simulation: Matlab 10 mexfunction() Purpose Validate the input and output, e.g., check: number, type, and size of arguments range of values and length of strings Allocate memory for output Preprocess the data Type conversion Call the computational routine(s) The computational routines can be part of the gateway routine (not recommended) Postprocess the data Modeling and Simulation: Matlab 11 mexfunction() mexfunction( int nlhs, mxarray *plhs[], int nrhs, const mxarray *prhs[] ) nlhs The number of left-hand arguments plhs An array of left-hand output arguments nrhs The number of right-hand arguments prhs An array of right-hand input arguments Modeling and Simulation: Matlab 12

Example 1 meanvec.c /* m = meanvec(v) computes the mean m of the values in the vector V. */ #include mex.h #define MAX(A, B) ((A) > (B)? (A) : (B)) #define MIN(A, B) ((A) < (B)? (A) : (B)) /* Compute the mean of the values in a vector */ double vmean(double *vec, int length) { int i; double sum = 0; for(i = 0; i < length; i++) { sum += vec[i]; return sum/length; meanvec.c (cont.) void mexfunction( int nlhs, mxarray *plhs[], int nrhs, const mxarray *prhs[]){ double *V; double mean; size_t m,n; /* Check number of arguments */ if (nrhs > 1) { mexerrmsgtxt("too many input arguments."); else if (nrhs < 1) { mexerrmsgtxt("not enough input arguments."); else if (nlhs > 1) { mexerrmsgtxt( Too many output arguments ); m = mxgetm(prhs[0]); /* Get number of rows */ n = mxgetn(prhs[0]); /* Get number of columns */ Modeling and Simulation: Matlab 13 Modeling and Simulation: Matlab 14 meanvec.c (cont.) /* Check dimension and type of input */ if (!mxisdouble(prhs[0]) mxiscomplex(prhs[0]) MIN(m,n)!= 1){ mexerrmsgtxt( V must be a non-empty real vector ); V = mxgetpr(prhs[0]); /* Get pointer to start-address */ /* Call computational routine */ mean = vmean(v,max(m,n)); /* Allocate memory for output argument and assign the mean value to it */ plhs[0] = mxcreatedoublescalar(mean); return; /* End of mexfunction */ Modeling and Simulation: Matlab 15 >> mex meanvec.c >> m = meanvec([1 2 3 4]) m = 2.5000 >> meanvec([1 2 3 4]) ans = 2.5000 >> [m,n] = meanvec([1 2 3 4])??? Too many output arguments >> m = meanvec([1 2 3 4],4)??? Too many input arguments. >> m = meanvec([1 2 3 4; 5 6 7 8])??? Input argument must be a non-empty real vector >> Modeling and Simulation: Matlab 16

Data types and macros mxarray (data type) Matlab array mwsize Array dimensions and number of elements mwindex Index values mwsize and mwindex are preprocessor macros included for cross-platform flexibility Some specific mex functions mxcalloc In a mex-file call mxcalloc to allocate memory (do not use calloc/malloc) mxfree Free memory allocated with mxcalloc mexprintf...as printf Modeling and Simulation: Matlab 17 Modeling and Simulation: Matlab 18 Error handling mexwarnmsgtxt issue a Matlab warning mexerrmsgtxt issue a Matlab error and return to Matlab. Allocated memory is freed before termination Matlab matrices in C Matlab stores (complex) matrices columnvise (C stores arrays row-vise) in two vectors: one contains the real data and one contains the imaginary data Pointer to each vector is obtained with mxgetpr and mxgetpi, respectively Modeling and Simulation: Matlab 19 Modeling and Simulation: Matlab 20

... matrices mxcreatedoublematrix Creates a 2-D matrix of type mxarray mxcreatesparse Create a 2-D sparse matrix mxcreatenumericalarray Creates an N-D matrix... etc... matrices mxgetpr Get pointer to first real element in an array mxgetpi Get pointer to first complex element in an array mxgetm / mxgetn Get number of rows/columns of an array mxdestroyarray Free memory allocated with mxcreate Modeling and Simulation: Matlab 21 Modeling and Simulation: Matlab 22 Example 2 lapacklu.c This example will use the routine dgetrf in the LAPACK library to compute the LUfactorization of a real matrix For syntax of the computational Fortran routine in LAPACK, see http://www.netlib.org/lapack/double/dgetrf.f lapacklu.c (cont.) To compile the source code the LAPACK library need to be included >> mex largearraydims lapacklu.c -lmwlapack Support of 64-bit API (64-bit integers) The LAPACK library is included with Matlab Modeling and Simulation: Matlab 23 Modeling and Simulation: Matlab 24

lapacklu test >> A = rand(5); >> [L,U,P] = lapacklu(a) L = 1.0000 0 0 0 0 0.3098 1.0000 0 0 0 0.5177 0.5538 1.0000 0 0 0.1236 0.0475 0.0414 1.0000 0 0.4995 0.9573 0.9230-0.6548 1.0000 U = 0.7803 0.1320 0.2348 0.1690 0.5470 0 0.9153 0.7485 0.6794 0.5753 0 0-0.5207 0.1840-0.4128 0 0 0 0.3902 0.6089 0 0 0 0 0.2522 P = 1 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 >> norm(a-p*l*u) ans = 1.2413e-16 Modeling and Simulation: Matlab 25 Mex configuration The option file for mex is mexopts.sh allocated in (search order): Current directory Matlabroot/bin The local preferences directory (returned by prefdir). On Linux, usually in Your home directory /.matlab/matlabversion/ To configure mex (e.g., to select compiler) type mex -setup in Matlab Modeling and Simulation: Matlab 26 Mex options -v Verbose -I<path> Search for header files in <path> -l<library> Link with library <library> -L<path> Search for libraries in <path> -D<name> Define the symbol <name> -output <name> Write output to <name>.mex Modeling and Simulation: Matlab 27 Makefile example MEX = mex MEXOPT = -O -largearraydims MEXLIBS = -lmwlapack MEXDEBUG = -g -DDEBUG RM = rm -f # Rules for targets default: all all : lapacklu clean lapacklu: @echo Compile MEX-file $(MEX) $(MEXOPT) -output $@ lapacklu.c $(MEXLIBS) @echo Done.. debug: # Makefile for lapacklu.c # # Targets: # * lapacklu: Create the mex file lapacklu.mex* # * debug: Compile mex-file with debug # information and trace outputs # * clean: Remove all object files. # Needed before compiling for a new # architecture. @echo Compile MEX-file for debugging $(MEX) $(MEXDEBUG) -output lapacklu lapacklu.c $(MEXLIBS) @echo Done.. clean: Modeling and $(RM) Simulation: *.omatlab 28

For more information Go to Matlab help Matlab External Interfaces Or visit: http://www.mathworks.se/access/helpdesk/help/t echdoc/matlab_external/bp_kqh7.html Modeling and Simulation: Matlab 29 Calling Java from Matlab Intergrated in Matlab (since Matlab 6) Can call native (built-in) as well as external Java classes directly from the Matlab command prompt The Java classes do not need to be compiled explicitly for Matlab No gateway function needed in the Java class Modeling and Simulation: Matlab 30 The other way around... Possible to call Matlab functions from an external program UNIX: Through pipes Windows: through a COM interface Use Matlab as computation engine Component Object Model Component Object Model (COM) Framework for integrating existing software into an application Software can be written in any language that supports COM The applications communicate through a COM object Modeling and Simulation: Matlab 31 Modeling and Simulation: Matlab 32

Calling Matlab from Java Compiled Matlab code Is officially not supported by Mathworks However... jmi.jar included to support this functionality Third-party Java-Matlab interfaces exist Compile your Matlab code to stand-alone applications or software Matlab is not needed by the end-user Requirements Matlab Compiler An ANSI C or C++ compiler Restrictions Do not work with all toolboxes (or parts of) Most pre-built GUIs can not be included Modeling and Simulation: Matlab 33 Modeling and Simulation: Matlab 34