开发者

Writing display-formatted strings to disk in MATLAB

Say I want to print to disk the output of the command magic(20) using the automatic formatting capabilities in MATLAB (i.e. thos开发者_运维百科e of display and disp)

I would like to do this programatically from MATLAB. So my take so far has been:

First I configure my formatting options.

format bank
format compact

Then I open a file in text mode and write permission:

fID = fopen('output_file.txt', 'wt');

And then, I try to save the output of specific statements to disk:

1) With num2str

string = num2str(magic(20));
fwritef(fID, '%s', string);

2) With eval (based on the most-voted answer on this thread)

string = eval('magic(20)');
fwritef(fID, '%s', string);

Is there any way to use display or disp in combination with fprintf (or a similar text-file-writing API) to write disp/display-formatted strings to disk?


If you're on linux or OS X you could run your script from the command line and redirect stdout to a file. You may want to check on the syntax, but it's something like

matlab -r my_function > out.txt

I think there's a way to do it from a DOSish prompt as well, though I don't know the redirect syntax there.

Update: Non-redirecting version

Does something like this work?

format bank
format compact

s1 = evalc('magic(4)');
s2 = evalc('disp(magic(4))');

f = fopen('test.txt', 'w');
fprintf(f, '%s', s1);
fprintf(f, '\n======================================\n\n');
fprintf(f, '%s', s2);
fclose(f)

If I run this and then do !cat test.txt, I get

ans =
     16.00          2.00          3.00         13.00
      5.00         11.00         10.00          8.00
      9.00          7.00          6.00         12.00
      4.00         14.00         15.00          1.00

======================================

     16.00          2.00          3.00         13.00
      5.00         11.00         10.00          8.00
      9.00          7.00          6.00         12.00
      4.00         14.00         15.00          1.00


Sounds like you want evalc. It will capture the command window output of an eval to a string.

x = magic(20);
str = evalc('disp(x)');
fprintf(fid, 'My matrix is:\n%s', str);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜