Read text file read a text file and create an matrix of data
3 次查看(过去 30 天)
显示 更早的评论
I have to read in matlab a file containing n lines of this type, I would need to put in matrix only the values after L and R, then Nx4 matrix. How can I do? I tried with readercsv and textscan but I failed. Thank you
TIMESTAMP: 636095415675460487 L 0,351316234728074 0,527804476880192 R 0,319373968641912 0,507390146614171
0 个评论
采纳的回答
Nick
2018-11-9
For this answer i am assuming your format does not change and you just have a file that is structured by just that line repeated with different values . In that case you can use textscan:
% Read all lines & collect in cell array
fid = fopen('textFile.txt');
txt = textscan(fid,'%s %s %s %s %s %s %s %s');
fclose(fid);
% reshape the cell array to be Nx8 (number of %s in your text scan)
txt = [txt{:}];
numericArray = str2double(txt); % convert to double, text will turn into nan
now you could go using the fact everything is a nan and the only other numeric value is the timestamp and use:
numericArray = numericArray(~isnan(numericArray));
numericArray = reshape(numericArray, [numel(numericArray)/5,5]);
numericArray = numericArray(:,2:end);
or you can use the indices of L and R and make a logical array based on them:
% find the columns for L and R, and their index
LPos = strcmp(txt(1,:), 'L');
RPos = strcmp(txt(1,:), 'R');
idxL = find(LPos);
idxR = find(RPos);
% create an vector thats only true for the numbers after L and R
mask = true(size(LPos));
mask(1:idxL) = false;
mask(idxR) = false;
% repeat the matrix for the number of rows inside your text file
mask = repmat(mask, size(txt, 1),1);
% apply the mask and reshape to be Nx4
numericArray = numericArray(mask);
numericArray = reshape(numericArray, [numel(numericArray)/4, 4]);
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Text Data Preparation 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!