Undocumented Matlab
  • SERVICES
    • Consulting
    • Development
    • Training
    • Gallery
    • Testimonials
  • PRODUCTS
    • IQML: IQFeed-Matlab connector
    • IB-Matlab: InteractiveBrokers-Matlab connector
    • EODML: EODHistoricalData-Matlab connector
    • Webinars
  • BOOKS
    • Secrets of MATLAB-Java Programming
    • Accelerating MATLAB Performance
    • MATLAB Succinctly
  • ARTICLES
  • ABOUT
    • Policies
  • CONTACT
  • SERVICES
    • Consulting
    • Development
    • Training
    • Gallery
    • Testimonials
  • PRODUCTS
    • IQML: IQFeed-Matlab connector
    • IB-Matlab: InteractiveBrokers-Matlab connector
    • EODML: EODHistoricalData-Matlab connector
    • Webinars
  • BOOKS
    • Secrets of MATLAB-Java Programming
    • Accelerating MATLAB Performance
    • MATLAB Succinctly
  • ARTICLES
  • ABOUT
    • Policies
  • CONTACT

Converting Java vectors to Matlab arrays

December 14, 2011 One Comment

Matlab includes built-in support for automatic conversion of Matlab cell arrays into Java arrays. This is important in cases when we need to pass information to a Java function that expects an array (e.g., String[]).

Numeric data array

In some cases, namely Java numeric arrays, Matlab also automatically converts the Java array into Matlab arrays. This is actually inconvenient when we would like to access the original Java reference in order to modify some value – since the Java reference is inaccessible from Matlab in this case, the data is immutable.

>> jColor = java.awt.Color.red
jColor =
java.awt.Color[r=255,g=0,b=0]
>> matlabData = jColor.getColorComponents([])
matlabData =
     1
     0     % < = immutable array of numbers, not a reference to int[]
     0

>> jColor = java.awt.Color.red jColor = java.awt.Color[r=255,g=0,b=0] >> matlabData = jColor.getColorComponents([]) matlabData = 1 0 % < = immutable array of numbers, not a reference to int[] 0

Non-numeric array

Very often we encounter cases in Java where the information is stored in an array of non-numeric data. In such cases we need to apply a non-automatic conversion from Java into Matlab.
If the objects are of exactly the same type, then we could store them in a simple Matlab array; otherwise (as can be seen in the example below), we could store them in either a simple array of handles, or in a simple cell array:

>> jFrames = java.awt.Frame.getFrames
jFrames =
java.awt.Frame[]:
    [javax.swing.SwingUtilities$SharedOwnerFrame ]
    [com.mathworks.mde.desk.MLMainFrame          ]
    [com.mathworks.mde.desk.MLMultipleClientFrame]
    [com.mathworks.mwswing.MJFrame               ]
% Alternative #1 - use a loop
>> mFrames = handle([]); for idx = 1 : length(jFrames); mFrames(idx)=handle(jFrames(idx)); end
>> mFrames
mFrames =
	handle: 1-by-4
>> mFrames(1)
ans =
	javahandle.javax.swing.SwingUtilities$SharedOwnerFrame
>> mFrames(2)
ans =
	javahandle.com.mathworks.mde.desk.MLMainFrame
% Alternative #2a - convert into a Matlab cell array
>> mFrames = jFrames.cell
mFrames =
    [1x1 javax.swing.SwingUtilities$SharedOwnerFrame ]
    [1x1 com.mathworks.mde.desk.MLMainFrame          ]
    [1x1 com.mathworks.mde.desk.MLMultipleClientFrame]
    [1x1 com.mathworks.mwswing.MJFrame               ]
% Alternative #2b - convert to a cell array (equivalent variant of alternative 2a)
>> mFrames = cell(jFrames);

>> jFrames = java.awt.Frame.getFrames jFrames = java.awt.Frame[]: [javax.swing.SwingUtilities$SharedOwnerFrame ] [com.mathworks.mde.desk.MLMainFrame ] [com.mathworks.mde.desk.MLMultipleClientFrame] [com.mathworks.mwswing.MJFrame ] % Alternative #1 - use a loop >> mFrames = handle([]); for idx = 1 : length(jFrames); mFrames(idx)=handle(jFrames(idx)); end >> mFrames mFrames = handle: 1-by-4 >> mFrames(1) ans = javahandle.javax.swing.SwingUtilities$SharedOwnerFrame >> mFrames(2) ans = javahandle.com.mathworks.mde.desk.MLMainFrame % Alternative #2a - convert into a Matlab cell array >> mFrames = jFrames.cell mFrames = [1x1 javax.swing.SwingUtilities$SharedOwnerFrame ] [1x1 com.mathworks.mde.desk.MLMainFrame ] [1x1 com.mathworks.mde.desk.MLMultipleClientFrame] [1x1 com.mathworks.mwswing.MJFrame ] % Alternative #2b - convert to a cell array (equivalent variant of alternative 2a) >> mFrames = cell(jFrames);

Note that if we only need to access a particular item in the Java vector or array, we could do that directly, without needing to convert the entire data into Matlab first. Simply use jFrames(1) to directly access the first item in the jFrames array, for example.
(note: Java Frames are discussed in chapters 7 and 8 of my Matlab-Java book).

Vectors and other Collections

Very often we encounter cases in Java where the information is stored in a Java Collection rather than in a simple Java array. The basic mechanism for the conversion in this case is to first convert the Java data into a simple Java array (in cases it was not so in the first place), and then to convert this into a Matlab array using either the automated conversion (if the data is numeric), or using a for loop (ugly and slow!), or into a cell array using the cell function, as explained above.
Different Collections have different manners of converting into a Java array: some Collections return an Iterator/Enumerator that can be processed in a loop (be careful not to reset the iterator reference by re-reading it within the loop):

% Wrong way - causes an infinite loop
idx = 1;
props = java.lang.System.getProperties;
while props.elements.hasMoreElements
    mPropValue{idx} = props.elements.nextElement;
end
% Right way
idx = 1;
propValues = java.lang.System.getProperties.elements;  % Enumerator
while propValues.hasMoreElements
    mPropValue{idx} = propValues.nextElement;
end

% Wrong way - causes an infinite loop idx = 1; props = java.lang.System.getProperties; while props.elements.hasMoreElements mPropValue{idx} = props.elements.nextElement; end % Right way idx = 1; propValues = java.lang.System.getProperties.elements; % Enumerator while propValues.hasMoreElements mPropValue{idx} = propValues.nextElement; end

(note: system properties are discussed in section 1.9 of my Matlab-Java book; Collections are discussed in section 2.1)
Other Collections, such as java.util.Vector, have a toArray() method that directly converts into a Java array, and we can process from there as described above:

>> jVector = java.util.Vector;
>> jVector.add(1); jVector.add(2); jVector.add(3);
>> jVector.addAll(jv); jVector.addAll(jv);
>> jVector
jVector =
[1.0, 2.0, 3.0, 1.0, 2.0, 3.0, 1.0, 2.0, 3.0, 1.0, 2.0, 3.0]
% Now convert into a Matlab cell array via a Java simple array
>> mCellArray = jVector.toArray.cell
mCellArray =
    [1]
    [2]
    [3]
    [1]
    [2]
    [3]
    [1]
    [2]
    [3]
    [1]
    [2]
    [3]

>> jVector = java.util.Vector; >> jVector.add(1); jVector.add(2); jVector.add(3); >> jVector.addAll(jv); jVector.addAll(jv); >> jVector jVector = [1.0, 2.0, 3.0, 1.0, 2.0, 3.0, 1.0, 2.0, 3.0, 1.0, 2.0, 3.0] % Now convert into a Matlab cell array via a Java simple array >> mCellArray = jVector.toArray.cell mCellArray = [1] [2] [3] [1] [2] [3] [1] [2] [3] [1] [2] [3]

Performance

It so happens, that the undocumented built-in feature function (or its near-synonym system_dependent) enables improved performance in this conversion process. feature(44) accepts a java.util.Vector and converts it directly into a Matlab cell-array, in one third to one-half the time that it would take the equivalent toArray.cell() (the third input argument is the number of columns in the result – the reshaping is done automatically):

>> mCellArray = feature(44,jVector,jVector.size)   % jVector.size = 12
mCellArray =
    [1]    [2]    [3]    [1]    [2]    [3]    [1]    [2]    [3]    [1]    [2]    [3]
>> mCellArray = feature(44,jVector,4)
mCellArray =
    [1]    [1]    [1]    [1]
    [2]    [2]    [2]    [2]
    [3]    [3]    [3]    [3]

>> mCellArray = feature(44,jVector,jVector.size) % jVector.size = 12 mCellArray = [1] [2] [3] [1] [2] [3] [1] [2] [3] [1] [2] [3] >> mCellArray = feature(44,jVector,4) mCellArray = [1] [1] [1] [1] [2] [2] [2] [2] [3] [3] [3] [3]

The conversion process is pretty efficient: On my system, the regular toArray.cell() takes 0.45 seconds for a 100K vector, compared to 0.21 seconds for the feature alternative. However, this small difference could be important in cases where performance is crucial, for example in processing of highly-active Java events in Matlab callbacks, or when retrieving data from a database. And this latter case is indeed where a sample usage of this feature can be found, namely in the cursor.fetch.m function (where it appears as system_dependent(44)).
Please note that both feature and system_dependent are highly prone to change without prior warning in some future Matlab release. On the other hand, the conversion methods that I presented above, excluding feature, will probably still be valid in all Matlab releases in the near future.

Related posts:

  1. Matlab-Java memory leaks, performance – Internal fields of Java objects may leak memory - this article explains how to avoid this without sacrificing performance. ...
  2. Using Java Collections in Matlab – Java includes a wide selection of data structures that can easily be used in Matlab programs - this article explains how. ...
  3. Java stack traces in Matlab – Matlab does not normally provide information about the Java calls on the stack trace. A simple trick can show us this information....
  4. Matlab callbacks for Java events – Events raised in Java code can be caught and handled in Matlab callback functions - this article explains how...
  5. Matlab-Java interface using a static control – The switchyard function design pattern can be very useful when setting Matlab callbacks to Java GUI controls. This article explains why and how....
  6. JBoost – Integrating an external Java library in Matlab – This article shows how an external Java library can be integrated in Matlab...
Java Performance Undocumented function
Print Print
« Previous
Next »
One Response
  1. Matlab-Java memory leaks, performance | Undocumented Matlab January 22, 2012 at 16:22 Reply

    […] of Objects that needs to be converted into a Matlab cell array using the built-in cell function, as described in one of my recent articles.The code is indeed innocent, works really well and is actually […]

Leave a Reply
HTML tags such as <b> or <i> are accepted.
Wrap code fragments inside <pre lang="matlab"> tags, like this:
<pre lang="matlab">
a = magic(3);
disp(sum(a))
</pre>
I reserve the right to edit/delete comments (read the site policies).
Not all comments will be answered. You can always email me (altmany at gmail) for private consulting.

Click here to cancel reply.

Useful links
  •  Email Yair Altman
  •  Subscribe to new posts (feed)
  •  Subscribe to new posts (reader)
  •  Subscribe to comments (feed)
 
Accelerating MATLAB Performance book
Recent Posts

Speeding-up builtin Matlab functions – part 3

Improving graphics interactivity

Interesting Matlab puzzle – analysis

Interesting Matlab puzzle

Undocumented plot marker types

Matlab toolstrip – part 9 (popup figures)

Matlab toolstrip – part 8 (galleries)

Matlab toolstrip – part 7 (selection controls)

Matlab toolstrip – part 6 (complex controls)

Matlab toolstrip – part 5 (icons)

Matlab toolstrip – part 4 (control customization)

Reverting axes controls in figure toolbar

Matlab toolstrip – part 3 (basic customization)

Matlab toolstrip – part 2 (ToolGroup App)

Matlab toolstrip – part 1

Categories
  • Desktop (45)
  • Figure window (59)
  • Guest bloggers (65)
  • GUI (165)
  • Handle graphics (84)
  • Hidden property (42)
  • Icons (15)
  • Java (174)
  • Listeners (22)
  • Memory (16)
  • Mex (13)
  • Presumed future risk (394)
    • High risk of breaking in future versions (100)
    • Low risk of breaking in future versions (160)
    • Medium risk of breaking in future versions (136)
  • Public presentation (6)
  • Semi-documented feature (10)
  • Semi-documented function (35)
  • Stock Matlab function (140)
  • Toolbox (10)
  • UI controls (52)
  • Uncategorized (13)
  • Undocumented feature (217)
  • Undocumented function (37)
Tags
AppDesigner (9) Callbacks (31) Compiler (10) Desktop (38) Donn Shull (10) Editor (8) Figure (19) FindJObj (27) GUI (141) GUIDE (8) Handle graphics (78) HG2 (34) Hidden property (51) HTML (26) Icons (9) Internal component (39) Java (178) JavaFrame (20) JIDE (19) JMI (8) Listener (17) Malcolm Lidierth (8) MCOS (11) Memory (13) Menubar (9) Mex (14) Optical illusion (11) Performance (78) Profiler (9) Pure Matlab (187) schema (7) schema.class (8) schema.prop (18) Semi-documented feature (6) Semi-documented function (33) Toolbar (14) Toolstrip (13) uicontrol (37) uifigure (8) UIInspect (12) uitable (6) uitools (20) Undocumented feature (187) Undocumented function (37) Undocumented property (20)
Recent Comments
Contact us
Captcha image for Custom Contact Forms plugin. You must type the numbers shown in the image
Undocumented Matlab © 2009 - Yair Altman
This website and Octahedron Ltd. are not affiliated with The MathWorks Inc.; MATLAB® is a registered trademark of The MathWorks Inc.
Scroll to top