poster
2019-12-10, 20:48
在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 如何以我的格式为可能为空的数值保留空间?
回答:
一种选择是使用函数CELLFUN (http://www.mathworks.com/help/techdoc/ref/cellfun.html)和NUM2STR (http://www.mathworks.com/help/techdoc/ref/num2str.html)首先将每个单元格更改为字符串,然后使用FPRINTF将 (http://www.mathworks.com/help/techdoc/ref/fprintf.html)每个单元格打印为字符串:
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的行。
更多&回答... (https://stackoverflow.com/questions/4127404)
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 如何以我的格式为可能为空的数值保留空间?
回答:
一种选择是使用函数CELLFUN (http://www.mathworks.com/help/techdoc/ref/cellfun.html)和NUM2STR (http://www.mathworks.com/help/techdoc/ref/num2str.html)首先将每个单元格更改为字符串,然后使用FPRINTF将 (http://www.mathworks.com/help/techdoc/ref/fprintf.html)每个单元格打印为字符串:
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的行。
更多&回答... (https://stackoverflow.com/questions/4127404)