在Matlab中动态格式化字符串

Sha*_*anu 5 arrays matlab printf

我正在尝试编写一个Matlab程序,该程序从用户那里获取要显示的行数的输入,并相应地打印如下内容:

1
2 2
3 3 3
Run Code Online (Sandbox Code Playgroud)

......等等

现在我可以使用两个for循环获得此输出,但是可以使用一个for循环执行相同操作吗?具体来说,我想知道是否有一种方法可以将for循环的迭代值传递给sprintf/fprintf语句,以类似于'%3d'的方式格式化字符串,以便sprintf/fprintf语句知道每行要打印多少变量.希望不是太乱.

谢谢!

山塔努.

Pea*_*oto 2

您可以简单地创建一个数组,每次传递到适当的大小,如下所示:

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
Run Code Online (Sandbox Code Playgroud)

请注意,如果将数组传递给fprintf语句,它将简单地重复该操作,直到数组完成。