MATLAB: fprintf/sprintf to print string + matrix

南楼画角 提交于 2020-01-11 13:29:29

问题


I wanted to know, if it's possible to print a string followed by a matrix, written in the classic form, for example:

                     5 5 9
>>your matrix is M = 1 4 2
                     2 1 3

using fprintf/sprintf.


回答1:


If your matrix doesn't have to be on the same line as the text, you can do something as simple as replacing ; with \n in the output of mat2str:

A=[1 2 3; 4 5 6; 7 8 9];
intro_str = 'Your matrix is:\n';
sprintf([intro_str strrep(mat2str(A),';','\n ')])

Your matrix is:
[1 2 3
 4 5 6
 7 8 9]

If, however, you want to have them on the same line, the only way I see how this can be done is by computing the amount of tabs (\t) or spaces you need on every "non-intro" line, approximately like this:

A=[1 2 3; 4 5 6; 7 8 9];

intro_str = 'Your matrix is: ';

%// ntabs = ceil(length(intro_str)/3);
%// tab_blanks = cellstr(repmat('\t',size(A,2),ntabs));
spaces = blanks(length(intro_str));
space_blanks = repmat(spaces,size(A,2),1);

mid_row = ceil(size(A,1)/2);

%// tab_blanks(mid_row) = {intro_str};
space_blanks(mid_row,:) = intro_str;

final_str = [space_blanks repmat('%u\t',size(A,1),size(A,2)) repmat('\n',size(A,1),1)]';
final_str = horzcat(final_str(:))';

sprintf(final_str,A(:))

ans =

                1   4   7   
Your matrix is: 2   5   8   
                3   6   9


来源:https://stackoverflow.com/questions/33482741/matlab-fprintf-sprintf-to-print-string-matrix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!