Read text file read a text file and create an matrix of data

3 ビュー (過去 30 日間)
Luca Vasapolli
Luca Vasapolli 2018 年 11 月 8 日
コメント済み: Luca Vasapolli 2018 年 11 月 10 日
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

採用された回答

Nick
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]);
  1 件のコメント
Luca Vasapolli
Luca Vasapolli 2018 年 11 月 10 日
Thanks for the reply, I solved by replacing the commas with the points and using simply
txt = textscan(...);
Thank you.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeText Files についてさらに検索

製品


リリース

R2015a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by