- Undocumented Matlab - https://undocumentedmatlab.com -

Converting Java vectors to Matlab arrays

Posted By Yair Altman On December 14, 2011 | 1 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

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);

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 [1] 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

(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 [2], 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]

Performance

It so happens, that the undocumented built-in feature function [3] (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]

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 [4], 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.

Categories: Java, Low risk of breaking in future versions


1 Comment (Open | Close)

1 Comment To "Converting Java vectors to Matlab arrays"

#1 Pingback By Matlab-Java memory leaks, performance | Undocumented Matlab On January 22, 2012 @ 16:22

[…] 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 […]


Article printed from Undocumented Matlab: https://undocumentedmatlab.com

URL to article: https://undocumentedmatlab.com/articles/converting-java-vectors-to-matlab-arrays

URLs in this post:

[1] Java Collection: http://docs.oracle.com/javase/tutorial/collections/index.html

[2] java.util.Vector: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Vector.html

[3] feature function: http://undocumentedmatlab.com/blog/undocumented-feature-function/

[4] processing of highly-active Java events in Matlab callbacks: http://undocumentedmatlab.com/blog/matlab-callbacks-for-java-events/

[5] Matlab-Java memory leaks, performance : https://undocumentedmatlab.com/articles/matlab-java-memory-leaks-performance

[6] Using Java Collections in Matlab : https://undocumentedmatlab.com/articles/using-java-collections-in-matlab

[7] Java stack traces in Matlab : https://undocumentedmatlab.com/articles/java-stack-traces-in-matlab

[8] Matlab callbacks for Java events : https://undocumentedmatlab.com/articles/matlab-callbacks-for-java-events

[9] Matlab-Java interface using a static control : https://undocumentedmatlab.com/articles/matlab-java-interface-using-static-control

[10] JBoost – Integrating an external Java library in Matlab : https://undocumentedmatlab.com/articles/jboost-integrating-an-external-java-library-in-matlab

Copyright © Yair Altman - Undocumented Matlab. All rights reserved.