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 (email)
  •  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
ActiveX (6) 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) uitools (20) Undocumented feature (187) Undocumented function (37) Undocumented property (20)
Recent Comments
  • Iñigo (2 days 15 hours ago): Thanks Yair. I didn’t realize it was posted just above. It would be great to know about a solution soon
  • Yair Altman (3 days 22 hours ago): @Iñigo – your query is related to Seth’s question above. We can access the currently-browsed URL in JavaScript (for example: jBrowserPanel.executeScript...
  • Iñigo (5 days 14 hours ago): I am looking for setting a UI that allows following process: opening a web site, navigate inside this web site and at some specific moments (i.e. when the figure is closed or a button...
  • Nicholas (12 days 20 hours ago): Yair, this works wonderfully! I can’t thank you enough!
  • Collin (14 days 23 hours ago): Seth Good point, I am using 2022b, mathworks seems to have started using CEF browsers from 2019a, best I can tell. take a look at the package com.mathworks.toolbox.matla...
  • Seth (15 days 15 hours ago): Collin, What version of MATLAB are you using?
  • Collin (20 days 22 hours ago): Seth, I have had some success executing javascript that requires no return value by executing it directly (sort of) on the org.cef.browser.CefBrowser that a...
  • Coo Coo (22 days 17 hours ago): FFT-based convolution is circular whereas MATLAB’s conv functions have several options (‘valid’, ‘same’, ‘full’) but unfortunately not...
  • Seth (22 days 19 hours ago): No luck with removing the space.
  • Seth (22 days 21 hours ago): The javascript code works fine running the application from the 2019b desktop version and the 2016b deployed version.
  • Seth (22 days 21 hours ago): I have been using this browser functionality in 2016b because it works fully in deployed applications in that version. However, because of Java 7 being flagged as a security risk, I...
  • Yair Altman (22 days 21 hours ago): I’ve never tested javascript callbacks, but perhaps you should try removing the extra space after the “matlab:” protocol specifier. Does it make any difference?
  • Seth (22 days 22 hours ago): I have been using this functionality in 2016b since it works in deployed applications and have not had a reason to need to upgrade but with java 7 being flagged as a security risk I am...
  • KEVIN (42 days 22 hours ago): I apologize, I intended my response to fall under ‘T’ but did not seem to work. I was referring to the bit of code posted by ‘T’ regarding the toolgroup and...
  • Yair Altman (42 days 23 hours ago): It is not clear from your comment which code exactly you are referring to and what you see differently in 19b vs. 20b, so I cannot assist with your specific query. In general I...
Contact us
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