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 结构
基础教程推荐
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 降序排序:Java Map 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01