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

2 vues (au cours des 30 derniers jours)
Luca Vasapolli
Luca Vasapolli le 8 Nov 2018
Commenté : Luca Vasapolli le 10 Nov 2018
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

Réponse acceptée

Nick
Nick le 9 Nov 2018
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 commentaire
Luca Vasapolli
Luca Vasapolli le 10 Nov 2018
Thanks for the reply, I solved by replacing the commas with the points and using simply
txt = textscan(...);
Thank you.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Text Data Preparation dans Help Center et File Exchange

Produits


Version

R2015a

Community Treasure Hunt

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

Start Hunting!

Translated by