需求:使用matlab读取txt文件的内容,并将其内容以一定的格式保存。
1. 源文件格式
目标文件格式
代码中使用打开文件读取的方式
%% 读取数据,转换为提取xyz的对应值
function ReadData()
[filename, pathname] = uigetfile('*.*', '选择数据文件','MultiSelect', 'on'); %选择文件
if isequal(filename,0) %判断是否选择
msgbox('没有选择任何数据文件');
else
pathfile1=fullfile(pathname, filename); %获得数据路径 {1}
end
name = strsplit(filename,'.'); % 写入的文件名由在源文件名后面+result.txt,目录相同
wpath = strcat(pathname, name(1));
wfile = strcat(wpath,'result.txt');
wfilename = cell2mat(wfile);
fir = fopen(pathfile1,'r');
fiw = fopen(wfilename, 'w');
DataValue = textscan(fir, '%s');
len = length(DataValue{1,1});
i = 1;
% 写入第一行
fprintf(fiw, 'x y z \r\n');
% 提取x y z数据, 提取的数据类型为cell,需要转化为char类型,使用class查看类型
while(i < len)
if(strcmp(DataValue{1,1}(i, 1), 'X:') == 1)
fprintf(fiw, '%s, %s, %s, \r\n',cell2mat(DataValue{1,1}(i + 1, 1)),...
cell2mat(DataValue{1,1}(i + 3, 1)),...
cell2mat(DataValue{1,1}(i + 5, 1)));...
i = i + 6;
else
i = i + 1;
end
end
end
2. 源文件中有一些多余的log,需要将有用的信息提取出来。
源文件如下,只需要提取有用的信息,APP这些log都不需要,这里涉及到ceil, 容易产生的问题如下
问题:索引必须在索引表达式的最后,比如查找第一个ceil数据中的第28个数DataValue{1,1}(28,1),若再查找第28个数据中第1个数据DataValue{1,1}{28,1}(1,1)(注意{} ())
实现方法,使用strfind('absfdgg','ab'), 查找前面的字符串是否包含后面的字符串。
或者使用strcmp(1,1) 1,查找是否存在相同的字符,若存在,返回1,不存在,返回0.