MATLAB:fprintf / sprintf打印字符串+矩阵

时间:2015-11-02 16:49:12

标签: matlab matrix vector printing printf

我想知道,如果可以打印字符串后跟矩阵,以经典形式编写,例如:

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

使用fprintf / sprintf

1 个答案:

答案 0 :(得分:3)

如果您的矩阵不必与文本位于同一行,您可以执行一些简单的操作,例如在mat2str的输出中将;替换为\n

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]

但是,如果你想让它们在同一条线上,我唯一能看到如何做到这一点的方法是计算每个&#34所需的标签数量(\t)或空格;非介绍"线,大概是这样的:

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