我有一个文本文件,其中包含如下行:
206,8,157,8,118,8,205,8,151,8,160,8,126,8,244,8,139,8,166,8,164,8,154,8,177,8,118,8,161,8,180,8,201,8,156,8
我想读取最初的 2 个数字,跳过接下来的 2 个数字,将接下来的 2 个数字等读入一个数组。由于文本文件很大,而且 Matlab 无法将所有数据保存在内存中,我一次读取一行。文本文件可能还有其他一些文本内容,我使用正则表达式忽略了这些内容。我的不完整代码如下:
fileID = fopen('4.dat'); %Open file
line= fgets(fileID); %read first line
testArray=[]; %Temporary array which will be appended to main array
I=[]; %Main array
while ischar(line)
fromX = regexp(line,'(\d*\,\d*\,){2,}','match'); %Find 2 consecutive numbers delimited by ","
fromXMat = cell2mat(fromX); %Convert to matrix
fromXMatNum = str2num(fromXMat); %Convert to numbers from string
testArray = fromXMatNum(1:2:numel(fromXMatNum)); %Read every 2nd number
I = [I,testArray]; %Append to main array
end
我也尝试过 textscan,但没有得到想要的结果。我想要以下输出:
Input: 206,8,157,8,118,8,205,8,151,8,160,8,126,8,244,8,139,8,166,8,164,8,154,8,177,8,118,8,161,8,180,8,201,8,156,8,
Output: 206,8,118,8,151,8,126,8,139,8,164,8,177,8,161,8,201,8
谢谢你的帮助。