Print A Matlab Struct to a Text File

后端 未结 4 1244
一向
一向 2020-12-21 18:18

I have a Matlab program which generates a set of very large structs as its output.
The structs are sufficiently large that I would like to be able to print the text repr

相关标签:
4条回答
  • 2020-12-21 18:22

    Old question, but IMO, the easiest solution is to use the evalc function. See console session below, that fails when trying to print a struct directly using fprintf, and also when trying to use the output of disp, but succeeds when using evalc:

    >> a = [1 2 3; 4 5 6]
    
    a =
    
         1     2     3
         4     5     6
    
    >> disp(whos('a'))
              name: 'a'
              size: [2 3]
             bytes: 48
             class: 'double'
            global: 0
            sparse: 0
           complex: 0
           nesting: [1×1 struct]
        persistent: 0
    
    >> fprintf('%s\n', whos('a'))
    Error using fprintf
    Function is not defined for 'struct' inputs.
     
    >> fprintf('%s\n', disp(whos('a')))
    Error using disp
    Too many output arguments.
     
    >> fprintf('%s\n', evalc('disp(whos(''a''))'))
              name: 'a'
              size: [2 3]
             bytes: 48
             class: 'double'
            global: 0
            sparse: 0
           complex: 0
           nesting: [1×1 struct]
        persistent: 0
    
    
    >> 
    

    evalc was introduced into Matlab before R2006a, so you should have no problems with compatibility.

    Just make sure you only ever use the evalc function if you can trust whatever will be used as the input; EG if you allow the input to evalc to be generated from user input, the user could potentially input malicious code, EG that could run a system command which compromises files on your PC etc. But if you use evalc on a hardcoded string, EG in the example above evalc('disp(whos(''a''))'), then you should be fine.

    0 讨论(0)
  • 2020-12-21 18:28

    You might consider using the struct2dataset command to formatting your result nicely before outputting it on the screen.

    0 讨论(0)
  • 2020-12-21 18:37

    There's no default Matlab function for saving of struct in a file (not that I'm aware of, at least). But there is struct2File function on File Exchange.

    0 讨论(0)
  • 2020-12-21 18:40

    The diary function is what you are looking for.

    0 讨论(0)
提交回复
热议问题