简体   繁体   English

快速Matlab矩阵到Java列表转换

[英]Fast Matlab Matrix to Java List conversion

I must massage data in a matrix of type 131072x1 int32 into a Java List<Integer> in Matlab. 我必须将类型为131072x1 int32的矩阵中的数据按到Matlab中的Java List<Integer>中。 So far, the only working conversion I've come up with is to roll through the values and directly add them to a LinkedList. 到目前为止,我提出的唯一有效的转换是遍历值并直接将它们添加到LinkedList。

count = size(data_flattened, 1);
ll = java.util.LinkedList;
for i = 1:count
    ll.add(data_flattened(i));
end

Which is slow in the extreme (5 seconds). 这是极端缓慢(5秒)。 I've tried several formulations of converting first to a Java array and then to a List but I always end up with an array with 1 column and 131072 rows. 我已经尝试了几种首先转换为Java数组然后转换为List配方,但我总是得到一个包含1列和131072行的数组。

I need a way of quickly assigning an N-by-1 Matlab matrix of int32s to a Java List<Integer> type. 我需要一种快速将int32s的N-by-1 Matlab矩阵分配给Java List<Integer>类型的方法。

Convert to a cell 转换为单元格

I found one way of getting Matlab to behave the way I want is to convert the matrix to cells. 我找到了一种让Matlab以我想要的方式运行的方法是将矩阵转换为单元格。

    cells = num2cell(data_flattened);        
    the_list = java.util.Arrays.asList(cells)

It is faster than rolling through the array and appending to the list, but it is still too slow. 它比滚动数组并附加到列表更快,但它仍然太慢。 On average 0.25 seconds per conversion which is better but still too high. 每次转换平均0.25秒,但更好但仍然太高。

Java 8 Stream Java 8 Stream

After some research and testing implementing a function in Java to handle the conversion to from an int[] to a List<Integer> in reasonable time (0.001 seconds). 经过一些研究和测试,在Java中实现一个函数,以便在合理的时间(0.001秒)内处理从int[]List<Integer>的转换。

public static List<Integer> flatten(int[] arr) {
    return IntStream.of(arr).parallel().boxed().collect(Collectors.toList());
}

To use Java 8 you'll need to point your MATLAB_JAVA environment variable to the newer JRE. 要使用Java 8,您需要将MATLAB_JAVA环境变量指向较新的JRE。 The location of your JRE can be found using java_home on a Mac. 可以使用Mac上的java_home找到JRE的位置。

/usr/libexec/java_home

Then in .bashrc or similar 然后在.bashrc或类似的

export MATLAB_JAVA="$(/usr/libexec/java_home)/jre"

Launching MATLAB from the terminal will now correctly pick up the new JRE. 从终端启动MATLAB现在可以正确地获取新的JRE。

In Matlab you can check your Java version 在Matlab中,您可以检查Java版本

version -java

and then in Matlab 然后在Matlab中

matlab_data_flattened = matlab_data(:);
java_list = com.my.package.ClassName.flatten(matlab_data_flattened);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM