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 结构
基础教程推荐
- 在springboot中如何给mybatis加拦截器 2023-04-29
- 控制台应用程序中的 Java 键盘输入解析 2022-01-01
- 将 double 转换为 Int,向下舍入 2022-01-01
- JPA惰性列表上的流 2022-01-01
- Java ECDSAwithSHA256 签名长度不一致 2022-01-01
- Maven:无效的目标版本:10 2022-01-01
- 将 Windows 证书导入 Java 2022-01-01
- 在java中使用xpath和selenium解析HTML表格数据 2022-01-01
- 如何在相机中应用自定义滤镜 [Surfaceview 预览]. 2022-01-01
- doFilter()是在servlet的工作完成之前还是之后执行的? 2022-01-01
