在 Java 对象中存储 MATLAB 结构 [英] Storing MATLAB structs in Java objects

查看:21
本文介绍了在 Java 对象中存储 MATLAB 结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 MATLAB 中使用 Java HashMap

I'm using Java HashMap in MATLAB

h = java.util.HashMap;

虽然字符串、数组和矩阵可以无缝地使用它

And while strings, arrays and matrices works seemlessly with it

h.put(5, 'test');

h.put(7, magic(4));

结构不

h=java.util.HashMap;
st.val = 7;
h.put(7, st);

??? No method 'put' with matching signature found for class 'java.util.HashMap'.




使它适用于结构的最简单/最优雅的方法是什么?

推荐答案

你需要确保从MATLAB传递到Java的数据可以正确转换.请参阅 MATLAB 的 External Interfaces 文档了解哪些类型被转换的转换矩阵其他类型.

You need to ensure that the data passed from MATLAB to Java can be properly converted. See MATLAB's External Interfaces document for the conversion matrix of which types get converted to which other types.

MATLAB 将大多数数据视为按值传递(具有句柄语义的类除外),并且似乎没有办法在 Java 接口中包装结构.但是您可以使用另一个 HashMap 来充当结构,并将 MATLAB 结构转换为 HashMap(对于多级结构、函数句柄和其他不能很好地与 MATLAB/Java 数据转换过程配合使用的野兽有一个明显的警告).

MATLAB treats most data as pass-by-value (with the exception of classes with handle semantics), and there doesn't appear to be a way to wrap a structure in a Java interface. But you could use another HashMap to act like a structure, and convert MATLAB structures to HashMaps (with an obvious warning for multiple-level structures, function handles, + other beasts that don't play well with the MATLAB/Java data conversion process).

function hmap = struct2hashmap(S)
if ((~isstruct(S)) || (numel(S) ~= 1))
    error('struct2hashmap:invalid','%s',...
          'struct2hashmap only accepts single structures');
end

hmap = java.util.HashMap;
for fn = fieldnames(S)'
    % fn iterates through the field names of S
    % fn is a 1x1 cell array
    fn = fn{1};
    hmap.put(fn,getfield(S,fn));
end

一个可能的用例:

>> M = java.util.HashMap;
>> M.put(1,'a');
>> M.put(2,33);
>> s = struct('a',37,'b',4,'c','bingo')

s = 

    a: 37
    b: 4
    c: 'bingo'

>> M.put(3,struct2hashmap(s));
>> M

M =

{3.0={a=37.0, c=bingo, b=4.0}, 1.0=a, 2.0=33.0}

>>

(读者练习:将其更改为递归地为本身就是结构的结构成员工作)

(an exercise for the reader: change this to work recursively for structure members which themselves are structures)

这篇关于在 Java 对象中存储 MATLAB 结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆