5

I have a Java array (my_array in the example below) in my MATLAB workspace that I would like to convert back to a MATLAB array.

whos my_array

  Name       Size            Class                                    

  my_array   20000x1            java.lang.Object[]

I could not find how to convert Java types back to MATLAB types in the External Interfaces documentation. The only thing I found is this (the documentation about MATLAB cells) which says that I can use MATLAB cells to do this task.

Using MATLAB cells seems an overkill, specially when I am handling thousands of elements of the same type (in this case, double). Is there any other way of moving Java objects back into MATLAB's native types?

3 Answers 3

6

Example:

%# example Object[] array
my_array = javaArray('java.lang.Object', 5);
for i=1:5, my_array(i) = java.lang.Double(i); end

%# convert to MATLAB vector
M = arrayfun(@(x)x, my_array);

%# or equivalently
M = cell2mat( cell(my_array) );

>> whos M
  Name      Size            Bytes  Class     Attributes

  M         5x1                40  double      
Sign up to request clarification or add additional context in comments.

1 Comment

The second one (cell2mat(cell(...))) is better, as it also works for 2d arrays.
2

when I am handling thousands of elements of the same type (in this case, double)

Are you in control of the Java code in question? If this is the case, return a double[] rather than a Double[] array or an Object[] array -- MATLAB will automatically convert a double[] array to a MATLAB vector of doubles.

1 Comment

How would I create a double[] in matlab ?
1

note that you can use the double function in matlab to convert java neumeric types to matlab internal.

ref http://www.kxcad.net/cae_MATLAB/techdoc/matlab_external/f6671.html#bq__508-1

function rv = convertJava2DToMatlab (javaArray) 
    numrows  = max (size (javaArray));
    numcols  = max (size (javaArray(1,:)));
    rv (numrows, numcols) = 1; % preallocating the matrix to optimize
    for i = 1:numrows
        for j = 1:numcols 
            if (javaArray(i,j) == 1) 
                rv (i,j) = double (javaArray(i,j));
            end
        end
    end
end % end of function convertJava2DtoMatlab                               

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.