MATLAB:fprintf/sprintf打印字符串+矩阵 [英] MATLAB: fprintf/sprintf to print string + matrix

查看:1189
本文介绍了MATLAB:fprintf/sprintf打印字符串+矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

使用fprintf/sprintf.

推荐答案

如果矩阵不必与文本位于同一行,则可以执行以下操作:将;替换为\n mat2str :

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]

但是,如果您希望将它们放在同一行上,那么我了解如何做到这一点的唯一方法是通过计算每个非前奏"上所需的制表符(\t)或空格的数量行,大致像这样:

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

这篇关于MATLAB:fprintf/sprintf打印字符串+矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆