我正在尝试编写一个 Matlab 程序,该程序从用户那里获取要显示的行数的输入,并相应地打印如下内容:
1
2 2
3 3 3
.. 很快
现在我可以使用两个 for 循环来获得这个输出,但是是否可以用一个 for 循环来做同样的事情?具体来说,我想知道是否有一种方法可以将 for 循环的迭代值传递给 sprintf/fprintf 语句,以类似于 '%3d' 的方式格式化字符串,以便 sprintf/fprintf 语句知道每行要打印多少个变量。希望那不是太混乱。
谢谢!
山塔努。
您可以简单地创建一个数组,每次传递到适当的大小,如下所示:
fid=1; % Will print out to the stdout, but can replace this with the folder to write to
for x=1:3
stuff=zeros(x,1)+x;
fprintf(fid,'%s ',stuff)
fprintf(fid,'\n');
end
请注意,如果将数组传递给fprintf语句,它将简单地重复它,直到数组完成。
尝试sprintf功能,这里是文档。比你做的事情:
sprintf('something %[flag][width].[precision][conversion] %...', arg1, ...)
对于整数小数,你可以这样做:
sprintf('%d', integer)