因此,我有一系列的显示函数,从x1到x7。它们都包含字符串和变量,如:
x1 = ['The result of the scalar multiplication of V and U: ',num2str(scalar_uv)]; x2 = similar to above but with for example a value on the cross multiplication of the two scalars.
而不是通过:disp(x1); disp(x2); disp(x3);逐个打印出来
我本以为可以通过一个for循环或嵌套的for循环将它们全部打印出来,但我就是想不出该怎么做。我最好不要直截了当的解决方案(我不会对它们说不),而是一些可能的提示或技巧。
发布于 2018-09-01 12:01:40
一个简单的示例解决方案是创建一个单元格阵列并对其进行循环,或者使用celldisp()来显示它。但是如果你想在命令窗口中很好地打印,也就是格式化,你可以使用fprintf函数并在格式中使用换行符。例如:
for displayValue = {x1, x2, x3, x4}
fprintf('%s\n', displayValue{1});
end如果需要更多格式选项,如精度或字段宽度,则格式规范代码(本例中为%s)有许多配置。你可以在fprintf helpdoc上看到它们。\n只是告诉fprintf函数在打印时创建一个换行符。
发布于 2018-09-03 19:08:27
不需要创建7个不同的变量(x1...x7),只需创建一个单元格数组来保存所有字符串:
x{1} = ['The result of the scalar multiplication of V and U: ',num2str(scalar_uv)];
x{2} = ['Some other statement with a value at the end: ',num2str(somevar)];现在您可以编写一个循环:
for iX = 1:length(x)
disp(x{iX})
end或者在没有for循环的情况下使用cellfun来显示它们:
cellfun(@disp,x)如果你真的想把它们命名为x1...x7,那么你可以使用eval语句来获得你的变量名:
for iX = 1:7
disp(eval(['x' num2str(iX)]));
endhttps://stackoverflow.com/questions/52120611
复制相似问题