You are on page 1of 12

2006-01-11

LiTH

RUT - development handbook 9.60 Extending MATLAB with Java v 2.0 - en


Per-Oskar Andersson

ABSTRACT
Sometimes MATLABs own programming language and components are insufficent for your programming needs. Using Java classes to extend MATLAB is a great way of doing so. Maybe there is a need to speed up a MATLAB function by writing it in Java or extending a MATLAB program with a database connection. This process description describes the integration of Java classes in MATLAB. It is not a complete description of the opportunities MATLAB offers. It meant to inform you of the possibilites and get you started. More information about communication between MATLAB and Java enviroments can be found by following the links under References.

RUT - development handbook 9.60 Extending MATLAB with Java v 2.0 - en

Field of application

1 Field of application
MATLAB is a widely spread program that is used in many different areas. There is a great need to use Java functions from within MATLAB since there are times when its build-in programming language is insufficient. Extending MATLAB with Java is modern and platform independent solution for this problem. Use this process description to understand how to extend MATLAB with the rich possibilites of the Java language. The MATLAB Java interface enables you to: Acess Java API (application programming interface) class packages that support essential activities such as I/O and networking. For example, the URL class provides convienient access to resources on the internet. Access third-party Java classes Easily construct Java objects in MATLAB Call Java object methods, using either Java or MATLAB syntax Pass data between MATLAB variables and Java objects

2 Prerequisites
The reader is assumed to possess basic knowledge about the programme MATLAB and also the programming language Java. Knowledge about data types and data structures is also necessary. It is assumed that the user works with MATLAB version 6.5 or later. The examples are created and tested with MATLAB version 7.0.

3 Realization
3.1 Overview
Defining Java classes
Java classes to be used in MATLAB can either be created by you, using numeros tools for Java development, standard library classes in the Java language or third party classes. When creating your own classes no adaption to the MATLAB enviroment is necessary. Creating the Java classes is beyond the scope of this document. See references for further reading.

Integrating Java classes with MATLAB


Integration of Java classes is easy and flexible, but some things must be kept in mind: that the classpath must be defined in MATLAB and how datatypes are converted between MATLAB and Java.

RUT - development handbook 9.60 Extending MATLAB with Java v 2.0 - en

Realization

3.2 Detailed description


In this section we cover the topic of Java integration with MATLAB in depth starting with a description of the Java class path in MATLAB. Defining the Java class path MATLAB loads Java class definitions from files that are on the Java class path. The class path is a series of file and directory specifications that MATLAB uses to locate class definitions. When loading a particular Java class, MATLAB searches files and directories in order they occur on the class path until a file is found that contains that class definitions. The first definition that is found ends the search. The Java class path consists of two segments: the static and the dynamic path. The static path is loaded at the start of each MATLAB session and cannot be changed without restarting MATLAB. The dynamic path can be loaded and modified at any time during a session using MATLAB functions. MATLAB always searches the static path before the dynamic path. The static path is defined in the file classpath.txt wich resides in the toolbox\local subdirectory of your MATLAB root directory. To find the complete path use this command in MATLAB:
[matlabroot '\toolbox\local\classpath.txt']

Edit this file to add and remove classes availible in MATLAB. To avoid changing the classpath of all users using the system, the classpath can be copied to your home directory. When MATLAB starts it will search the current directory for classpath.txt and use it if present. The dynamic path can be changed at runtime, with the commands javaclasspath, javaaddpath and javarmpath. See refereces for further documentation on these commands. The flexibility of changing the classpath at runtime is an advantage comparing to the static path, but the classes are loaded slower than on the static path. Use the dynamic path under development and put the classes in the static path when you decided wich classes to use. Creating Java objects Java objects can be created with the standard Java syntax:
object = classname(constrArg1,..,constrArgn)

Alternatively, you can use the MATLAB command javaObject:


object = javaObject(classname,constArg1,..,constArgn)

The advantage of this method is that the class name can be specified at runtime.

RUT - development handbook 9.60 Extending MATLAB with Java v 2.0 - en

Realization

Using Java and MATLAB calling syntax To call methods on Java objects, you can use the Java syntax:
object.method(arg1,...,argn)

Alternatively, you can call (nonstatic) methods with the MATLAB syntax:
method(object,arg1,..,argn)

Simplifying Java Class Names In MATLAB you can refer to any Java class by its fully qualified name, which include its package name, but a fully qualified name can be rather long and make the code hard to read. Instead you can use the MATLAB import command and then use only the class name without the package prefix. Examples:
import class_name

Imports a single class.


import pkg_name.*

Imports all classes in the package. Passing data to a Java method When you make a call from MATLAB to Java code, any MATLAB data types passed in the call are converted to data types native to the Java language. MATLAB performs this conversion on each argument that is passed, except for those arguments that are already Java objects. This table below describes the conversion that is performed on specific MATLAB data types.

Table 2: Conversion of MATLAB types


MATLAB argument double(logical) double single char uint8 uint16 uint32 int8 int32 Java object Converted Java type: boolean double float String byte short int byte int Object

RUT - development handbook 9.60 Extending MATLAB with Java v 2.0 - en

Realization

Handling data returned from a Java method In many cases, data returned from Java is incompatible with the data types operated on whithin MATLAB. When this is the case, MATLAB converts the returned value to a data type native to the MATLAB language. The types in the table below are converted and all other types (eg. Java objects)are stored in MATLAB in ther original form.

Table 3: Conversion of Java types


Java return type boolean byte short int long float double char Scalar return, resuling MATLAB type double(logical) double double double double double double char Array return, resulting MATLAB type double(logical) int8 int16 int32 double single double char

Handling Java Exceptions If a Java method or constructor is invoked, that throws an exception, MATLAB catches the exception and transforms it into a MATLAB error. MATLAB puts the text of the Java error message into its own error message. Receiving an error from a Java method or constructor has the same apperance as receiving an error from an M-file. Determining the Class of an Object To find the class of a java object, use the query form of the MATLAB function class:
classname = class(object)

The classname is returned as a matlab char array. This command works with MATLAB objects as well. To find out if it is a Java object or not, use the isjava function:
objecttype = isjava(object)

Object type is 1 if object is a Java object, 0 if not.

RUT - development handbook 9.60 Extending MATLAB with Java v 2.0 - en

Results

Converting Objects to MATLAB data types With the exception of the types listed in Table 2, MATLAB does not convert Java objects returned from method calls to a native MATLAB data type. If you want to convert Java object data to a form useable in MATLAB, there are a few MATLAB functions that enable you to do this. Use the double function in MATLAB to convert any Java object or array of objects to the MATLAB format double. Note that the specified object must inherit from java.lang.number or implement a toDouble function. Otherwise MATLAB will report an error. Use the char function in MATLAB to convert java.lang.String objects to MATLAB character arrays. An array of java.lang.String objects results in a MATLAB cell array containing character arrays. Note that if the object type is not of the java.lang.String class or does not implement a toChar method, MATLAB will report an error. Use the cell function to convert a Java array or Java object into a MATLAB cell array. Element of the resulting cell array will be of the MATLAB type closest to the Java array element or Java object. The syntax for these commands are displayed below:
matlab_double = double(object) matlab_char = char(object) matlab_cell = cell(object)

Saving and loading Java objects to MAT-files Use the MATLAB save function to save a Java object to a MAT-file. Use the load function to load it back into MATLAB from that MAT-file. To save a Java object to a MAT-file make sure that the object and its class implements the serializable interface (part of the Java API), either directly inheriting it from a parent class. Any embedded or otherwise referenced objects must also implement the Serializable interface.

4 Results
4.1 Products
The result is an extension of MATLAB in the form of a MATAB m-file or a set of commands to utilize the new functionality. If you develop the Java classes yourself, these are also part of the result.

RUT - development handbook 9.60 Extending MATLAB with Java v 2.0 - en

Templates and forms

4.2 Product templates

5 Templates and forms 6 Verification of results


If you develop the Java clases to be integrated in MATLAB, these should of course be checked and tested with appropriate methods. The integration should then be tested from within MATLAB. A description of these kinds of methods can be found in other process descriptions.

7 Examples with explanations


7.1 Reading a URL
This example, opens a connection to a web site specified by a URL (Uniform Resource Locator) for the purpose of reading text from a file at that site. It constructs an object of the Java API class java.net.URL, which enables convienient handling of URLs. Then, it calls a method on the URL object, to open a connection and display some lines of text. The example displays how easy it is to extend MATLAB with Java. The following code can be saved to a M-file for easy editing and testing in MATLAB.
%% readurl.m %% Construct a URL Object url = java.net.URL('http://www.ida.liu.se/~TDDC02/'); %% %% %% is Open a Connection to the URL. Use openStream method, opening a connection with the website and returning an InputStream object. = openStream(url);

%% Set up a buffered stream reader isr = java.io.InputStreamReader(is); br = java.io.BufferedReader(isr); %% Skip initial html formatting lines for k = 1:30 s = readLine(br); end %% Read 8 lines of text c = ''; for k = 1:8 s = readLine(br); %% This is a java.lang.String object %% Concatenate the strings into a MATLAB char array c = strvcat(c, char(s)); end %% Display the result c

RUT - development handbook 9.60 Extending MATLAB with Java v 2.0 - en

Examples with explanations

7.2 Finding an Internet Protocol adress


This example returns either the name or adress of an IP (internet protocol) host. If you pass resolveip a hostname, it displays the IP adress. If you pass resolveip an IP adress, it displays the hostname. The example contains catching of Java exceptions, importing a classname, and converting between Java and MATLAB types. The code should be written to a matlab M-file.
%% resolveip.m function resolveip(input) %% import class name import java.net.InetAdress.* %% try to resolve IP adress, catch error if not found try adress = java.net.InetAddress.getByName(input); catch error(sprintf('Unknown host %s.', input)); end %% convert hostname and IP adress to matlab char arrays hostname = char(adress.getHostName) ipadress = char(adress.getHostAddress) %% display hostname or IP adress if strcmp(input,ipadress) disp(sprintf('Hostname of %s is %s', input, hostname)); else disp(sprintf('IP adress of %s is %s', input, ipadress)); end

7.3 Graphical user interface


This example creates a simple table which is displayed in a new window. The headers and the data of the table is taken as inputs. There is no real user interaction in this simple example, but it shows one way of displaying a separate graphical window using java. The code should be written to a matlab Mfile.
%% gui.m function gui(title, data) import com.mathworks.mwt.* java.awt.*; %% title is a string %% data is a cell array of strings, where the first row are headers. %% Usage: %% gui('a table', {'a', 'b', 'c'; '1', '2', '3'; '4', '5', '6'})

RUT - development handbook 9.60 Extending MATLAB with Java v 2.0 - en

Examples with explanations

handle=MWFrame(title); colwidth = 100; rowheight = 32; [nrows, ncolumns]=size(data); b = MWListbox; b.setColumnCount(ncolumns); for i=1:ncolumns, b.setColumnWidth(i-1 ,colwidth); b.setColumnHeaderData(i-1,data{1,i}); % b.setRowHeight(i-1,rowheight); end; %% Set the behaviour of the table b.setExcelMode(1); ts=b.getTableStyle; ts.setVGridVisible(1); ts.setHAlignment(1); b.setTableStyle(ts); co = b.getColumnOptions; set(co, 'HeaderVisible', 'on'); set(co, 'Resizable', 'on'); b.setColumnOptions(co); %% Fill up the table with data: text={}; for i=2:nrows for j=1:ncolumns text{1,j}=mat2str(data{i,j}); end b.addItem(text); text={}; end b.setSelectedIndex(0); handle.add(b); handle.setBounds(300,300,colwidth*ncolumns,rowheight*nrows); %% Make the window closeable handle.addWindowListener(window.MWWindowActivater(handle)); handle.setVisible(1);

RUT - development handbook 9.60 Extending MATLAB with Java v 2.0 - en

Solutions to common problems

8 Solutions to common problems


Are you unable to use a Java class? Solution: check Java class path. You changed the Java class file, but the class acts the same. Solution: restart MATLAB You keep getting out of memory errors after using MATLAB for a while. Solution: make sure to delete old objects.

9 Adjustment to the PUM-course


Adjustments havent been necessary to perform.

10 Measurement of the process


10.1 Resource measurement
Programming often takes more time than anticipated. If you develop the Java classes yourself, you should test these seperatly to save time before integrating them with MATLAB. MATLAB code takes longer time to debug then Java code so to try to put as much functionality into the Java classes as possible.

10

RUT - development handbook 9.60 Extending MATLAB with Java v 2.0 - en

History of the process

10.2 Product measurement 10.3 Forms for collection of data

11 History of the process


Table 1: History of the process
Version 1.0 2.0 Date 05-01-10 06-01-11 Editor Hans Holmberg Per-Oskar Andersson First version Second version. Corrected spelling errors. Updated the examples and added example 7.3. References was updated. Comments

12 Changes not yet attended to


A section on how to make interactive graphical user interfaces written in Java, which uses MATLAB functions would be a good extention of this document.

13 References
13.1 Method description
MATLAB External Interfaces/API, http://www.mathworks.com/access/helpdesk/help/techdoc/rn/external_new.html. MATLAB External Interfaces/API Reference, http://www.mathworks.com/access/helpdesk/help/techdoc/apiref/apiref.shtml. MATLAB Central/ Utilities, http://www.mathworks.com/matlabcentral/fileexchange/loadCategory.do?objectId=8&objectType=Category Java in a Nutshell, David Flanagan 4th edition 2002

13.2 Method evaluation 13.3 Internal comments


Some chapters have intentionally been left blank since nothing of importance can be said.

RUT - development handbook 9.60 Extending MATLAB with Java v 2.0 - en

11

References

12

RUT - development handbook 9.60 Extending MATLAB with Java v 2.0 - en

You might also like