Advertisement
Guest User

Untitled

a guest
Jun 24th, 2019
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.58 KB | None | 0 0
  1. [[1,2,[3]],4] -> [1,2,3,4]
  2.  
  3. a.c = [5,4];
  4. a.b.a=[9];
  5. a.b.d=[1,2];
  6.  
  7. a= b: [1x1 struct]
  8. c: [5 4]
  9.  
  10. output= [9,1,2,5,4]
  11.  
  12. function C = flatten_struct(A)
  13.  
  14. A = struct2cell(A);
  15. C = [];
  16. for i=1:numel(A)
  17. if(isstruct(A{i}))
  18. C = [C,flatten_struct(A{i})];
  19. else
  20. C = [C,A{i}];
  21. end
  22. end
  23.  
  24. end
  25.  
  26. a.c = [5,4];
  27. a.b.a=[9];
  28. a.b.d=[1,2];
  29.  
  30. flatten_struct(a)
  31.  
  32. ans =
  33.  
  34. 5 4 9 1 2
  35.  
  36. % struct2sims converter
  37. function simout = struct2sims(structin)
  38. fnam = fieldnames(structin);
  39. for jf = 1:numel(fnam)
  40. subnam = [inputname(1),'_',fnam{jf}];
  41. if isstruct(structin.(fnam{jf}) ) ,
  42. % need to dive; build a new variable that's not a substruct
  43. eval(sprintf('%s = structin.(fnam{jf});', fnam{jf}));
  44. eval(sprintf('simtmp = struct2sims(%s);',fnam{jf}) );
  45. % try removing the struct before getting any farther...
  46. simout.(subnam) = simtmp;
  47. else
  48. % at bottom, ok
  49. simout.(subnam) = structin.(fnam{jf});
  50. end
  51.  
  52. end
  53. % need to unpack structs here, after each level of recursion
  54. % returns...
  55. subfnam = fieldnames(simout);
  56. for kf = 1:numel(subfnam)
  57. if isstruct(simout.(subfnam{kf}) ),
  58. subsubnam = fieldnames(simout.(subfnam{kf}));
  59. for fk = 1:numel(subsubnam)
  60. simout.([inputname(1),'_',subsubnam{fk}])...
  61. = simout.(subfnam{kf}).(subsubnam{fk}) ;
  62. end
  63. simout = rmfield(simout,subfnam{kf});
  64. end
  65. end
  66. % if desired write to file with:
  67. % save('flattened','-struct','simout');
  68. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement