code_junkie

Storing MATLAB structs in Java objects

Nov 13th, 2011
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.17 KB | None | 0 0
  1. h = java.util.HashMap;
  2.  
  3. h.put(5, 'test');
  4.  
  5. h.put(7, magic(4));
  6.  
  7. h=java.util.HashMap;
  8. st.val = 7;
  9. h.put(7, st);
  10.  
  11. ??? No method 'put' with matching signature found for class 'java.util.HashMap'.
  12.  
  13. function hmap = struct2hashmap(S)
  14. if ((~isstruct(S)) || (numel(S) ~= 1))
  15. error('struct2hashmap:invalid','%s',...
  16. 'struct2hashmap only accepts single structures');
  17. end
  18.  
  19. hmap = java.util.HashMap;
  20. for fn = fieldnames(S)'
  21. % fn iterates through the field names of S
  22. % fn is a 1x1 cell array
  23. fn = fn{1};
  24. hmap.put(fn,getfield(S,fn));
  25. end
  26.  
  27. >> M = java.util.HashMap;
  28. >> M.put(1,'a');
  29. >> M.put(2,33);
  30. >> s = struct('a',37,'b',4,'c','bingo')
  31.  
  32. s =
  33.  
  34. a: 37
  35. b: 4
  36. c: 'bingo'
  37.  
  38. >> M.put(3,struct2hashmap(s));
  39. >> M
  40.  
  41. M =
  42.  
  43. {3.0={a=37.0, c=bingo, b=4.0}, 1.0=a, 2.0=33.0}
  44.  
  45. >>
  46.  
  47. % Must initialize with a dummy value to allow numeric keys
  48. m = containers.Map(0, 0, 'uniformValues',false);
  49. % Remove dummy entry
  50. m.remove(0);
  51.  
  52. m(5) = 'test';
  53. m(7) = magic(4);
  54. m(9) = struct('foo',42, 'bar',1:3);
  55. m(5), m(7), m(9) % get values back out
  56.  
  57. h = java.util.HashMap;
  58. carr = {7, 'hello'};
  59. h.put(7, carr);
  60.  
  61. % OR
  62.  
  63. h = java.util.HashMap;
  64. st.val = 7;
  65. h.put(7, struct2cell(st));
Add Comment
Please, Sign In to add comment