matlab怎么逐行读取txt文件内容,转载:matlab 逐行 读取 txt 文件

转载自:http://blog.sciencenet.cn/blog-762216-1086021.html

% The load function can be used to load txt file, in which each row has the same number of elements.

% This script (read_line) is to read the txt file, in which the last row have a different number of elements.

clear

clc

%re=load('xxx.txt');

re=int16(zeros(1e6,23));  %预定义矩阵,加快速度

fid=fopen('xxx.txt');  %打开文本文件

INDEX=0;

while ~feof(fid)

str = fgetl(fid);   % 读取一行, str是字符串

s=regexp(str,'\s+');   % 找出str中的空格, 以空格作为分割数据的字符

temp=str2num(str(s(end):end));    %找出最后的数据, 作为保存与否的判断条件

%temp=str2num(str(s(20):s(21)));  %找出某个数据, 作为保存与否的判断条件

if temp>10

INDEX=INDEX+1;

for i=1:length(s)   % 将字符串全部转为数组, 存于re中

if i==length(s)

re(INDEX,i)=str2num(str(s(i):end));

else

re(INDEX,i)=str2num(str(s(i):s(i+1)));

end

end

end

end

fclose(fid);

%re2=re(1:INDEX,:);

%dlmwrite(strcat('.\re'),re2,'precision','%2d', 'delimiter', ' ');  % save re

本文链接:https://my.lmcjl.com/post/13102.html

展开阅读全文

4 评论

留下您的评论.