Storing MATLAB structs in Java objects(在 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 结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Java 对象中存储 MATLAB 结构
- Jersey REST 客户端:发布多部分数据 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01