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
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.
You might consider using the struct2dataset command to formatting your result nicely before outputting it on the screen.
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.
The diary function is what you are looking for.