当我使用sprintf时,结果如下:
sprintf('number=%d %d %d',a,b,c)
sprintf('or %d',h)
ans =
number= 5 4 2
ans =
or 2
如何在不受ans =
干扰的情况下显示结果?
可以用fprintf
代替sprintf
。记住在字符串的末尾加上一个换行符n
。
总结
选项1: disp(['A string: ' s ' and a number: ' num2str(x)])
选项2: disp(sprintf('A string: %s and a number %d', s, x))
选项3: fprintf('A string: %s and a number %dn', s, x)
引用http://www.mathworks.com/help/matlab/ref/disp.html(在同一行显示多个变量)
有三种方法可以在命令窗口的同一行显示多个变量。
(1)使用[]操作符将多个字符串连接在一起。使用num2str函数将任何数值转换为字符。然后,使用disp显示字符串。
name = 'Alice';
age = 12;
X = [name,' will be ',num2str(age),' this year.'];
disp(X)
Alice will be 12 this year.
(2)您也可以使用sprintf来创建字符串。以分号结束sprintf命令,以防止显示"X ="。然后,使用disp显示字符串。
name = 'Alice';
age = 12;
X = sprintf('%s will be %d this year.',name,age);
disp(X)
Alice will be 12 this year.
(3)或者,使用fprintf创建并显示字符串。与sprintf函数不同,fprintf不显示"X = "文本。但是,您需要以换行符(n)元字符结束字符串以正确终止其显示。
name = 'Alice';
age = 12;
X = fprintf('%s will be %d this year.n',name,age);
Alice will be 12 this year.