![]() |
如何获得fprintf来保留一个空数值的空间?
在MATLAB中,我使用fprintf在列标题下打印数值列表,如下所示:
fprintf('%s %s %s %s\n', 'col1', 'col2', 'col3', 'col4') for i = 1:length(myVar) fprintf('%8.4g %8.4g %8.4g %8.4g\n', myVar{i,1}, myVar{i,2}, myVar{i,3}, myVar{i,4}) end 结果是这样的: col1 col2 col3 col4 123.5 234.6 345.7 456.8 但是,当其中一个单元为空时(例如, myVar{i,3} == [] ),将不保留空间: col1 col2 col3 col4 123.5 234.6 456.8 如何以我的格式为可能为空的数值保留空间? [B]回答:[/B] 一种选择是使用函数[URL="http://www.mathworks.com/help/techdoc/ref/cellfun.html"]CELLFUN[/URL]和[URL="http://www.mathworks.com/help/techdoc/ref/num2str.html"]NUM2STR[/URL]首先将每个单元格更改为字符串,然后使用[URL="http://www.mathworks.com/help/techdoc/ref/fprintf.html"]FPRINTF将[/URL]每个单元格打印为字符串: fprintf('%8s %8s %8s %8s\n', 'col1', 'col2', 'col3', 'col4'); for i = 1:size(myVar,1) temp = cellfun(@(x) num2str(x,'%8.4g'),myVar(i,:),'UniformOutput',false); fprintf('%8s %8s %8s %8s\n',temp{:}); end 这应该为您提供如下输出: col1 col2 col3 col4 123.5 234.6 456.8 还要注意,我在第一个FPRINTF调用中添加了8,以修复列标签的格式,并将length(myVar)更改为size(myVar,1)因为您正在遍历myVar的行。 [url=https://stackoverflow.com/questions/4127404]更多&回答...[/url] |
所有时间均为北京时间。现在的时间是 23:27。 |
Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.