如何解决fprintf 格式的问题Matlab
我想使用下一个 Matlab 代码(先前导入)更正 txt 文件中的变量格式(最后显示,替换制表符空格的空格):
id = fopen('datoscorfecha.txt','w');
fprintf(id,'%5s %3s %3s %3s %4s %3s %6s\n',...
'fecha','dia','mes','ano','hora','min','abs370');
datos = cat(2,dia,mes,ano,hora,min1,abs370);
datos = datos';
fecha = Fecha'; % Imported as a string
fprintf(id,'%16s %2i %2i %4i %2i %2i %8.4f\n',...
fecha,datos);
fclose(id);
type datoscorfecha.txt
但我收到此错误:
使用 fprintf 时出错 无法将“字符串”值转换为 'int64'。
Fecha dia mes ano hora min abs370
03/06/2016 00:00 3 6 2016 0 0 29.356218
03/06/2016 00:05 3 6 2016 0 5 30.45703
03/06/2016 00:10 3 6 2016 0 10 27.53877
03/06/2016 00:15 3 6 2016 0 15 23.19832
03/06/2016 00:20 3 6 2016 0 20 22.333924
03/06/2016 00:25 3 6 2016 0 25 22.086426
03/06/2016 00:30 3 6 2016 0 30 20.933898
解决方法
也许这样的东西可以让你用制表符替换空格。在这里,我使用 textscan()
函数读取文本文件并分隔列。我还将每个值/术语解析为字符串。通过使用 writematrix()
函数,我可以将数据写入一个新的文本文件,但将 Delimeter
设置为 tab
。
Text.txt(输入)
Fecha dia mes ano hora min abs370
03/06/2016 00:00 3 6 2016 0 0 29.356218
03/06/2016 00:05 3 6 2016 0 5 30.45703
03/06/2016 00:10 3 6 2016 0 10 27.53877
03/06/2016 00:15 3 6 2016 0 15 23.19832
03/06/2016 00:20 3 6 2016 0 20 22.333924
03/06/2016 00:25 3 6 2016 0 25 22.086426
03/06/2016 00:30 3 6 2016 0 30 20.933898
datoscorfecha.txt(输出)
Fecha dia mes ano hora min abs370
03/06/2016 00:00 3 6 2016 0 0 29.3562
03/06/2016 00:05 3 6 2016 0 5 30.4570
03/06/2016 00:10 3 6 2016 0 10 27.5388
03/06/2016 00:15 3 6 2016 0 15 23.1983
03/06/2016 00:20 3 6 2016 0 20 22.3339
03/06/2016 00:25 3 6 2016 0 25 22.0864
03/06/2016 00:30 3 6 2016 0 30 20.9339
完整脚本:
File_ID = fopen("Text.txt");
Data = textscan(File_ID,'%s %s %s %s %s %s %s %s','Delimiter',' ');
fclose(File_ID);
% Data = readtable("Text.txt");
Column_1 = string(Data{:,1});
Column_2 = string(Data{:,2});
Column_3 = string(Data{:,3});
Column_4 = string(Data{:,4});
Column_5 = string(Data{:,5});
Column_6 = string(Data{:,6});
Column_7 = string(Data{:,7});
Column_8 = string(Data{:,8});
for Index = 2: length(Column_8)
Number = str2double(char(Column_8(Index,1)));
Number = num2str(Number);
Decimal_String = split(Number,".");
Decimal_String = Decimal_String{2};
if length(Decimal_String) ~= 4
Number = string(Number) + "0";
end
Column_8(Index,1) = Number;
end
Table = [Column_1 Column_2 Column_3 Column_4 Column_5 Column_6 Column_7 Column_8];
writematrix(Table,"datoscorfecha.txt",'tab');
type datoscorfecha.txt
使用 MATLAB R2019b 运行
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。