Novak
Novak

Reputation: 4783

Print A Matlab Struct to a Text File

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 representations to a text file for later study.

I.e., the command:

foo(1)

sends the first of the structs to the screen, but the structure is too large to fit in the scroll window, and the scroll window is a poor tool for looking at such a large block of text, anyway. I would like to be able to pipe the output of that command directly to a text file.

Unfortunately, fprintf is not defined for some elements in the struct, and so fprintf fails. Likewise, I believe the WriteStructsToText.m script, which is part of the Psychtoolbox library, also fails.

Is there any way to force Matlab to just dump what it is displaying on the screen directly into a text file?

Upvotes: 2

Views: 10420

Answers (4)

Jake Levi
Jake Levi

Reputation: 1730

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.

Upvotes: 2

ZZZ
ZZZ

Reputation: 724

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

Upvotes: 1

johnish
johnish

Reputation: 390

The diary function is what you are looking for.

Upvotes: 7

plesiv
plesiv

Reputation: 7028

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.

Upvotes: 1

Related Questions