How to read .raw files of unknown number of rows and 9 columns

3 vues (au cours des 30 derniers jours)
trent
trent le 10 Juin 2016
Commenté : trent le 10 Juin 2016
I have multiple .raw files of format:
-1.1972430e+00 1.9116530e+00 -1.6151377e+01 -1.6761160e+00 1.3295020e+00 -1.5595563e+01 -1.3040950e+00 1.6830060e+00 -1.5456139e+01
-1.1972430e+00 1.9116530e+00 -1.6151377e+01 -1.8009150e+00 1.4511150e+00 -1.6474810e+01 -1.6761160e+00 1.3295020e+00 -1.5595563e+01
-1.1559240e+00 2.0341980e+00 -1.6435989e+01 -1.8009150e+00 1.4511150e+00 -1.6474810e+01 -1.1972430e+00 1.9116530e+00 -1.6151377e+01
.
.
.
2.2807209e+00 2.8720999e-02 -1.0023850e+00 2.3006320e+00 2.7641000e-02 -7.0393997e-01 2.3620090e+00 3.5114399e-01 -8.2908899e-01
2.3591161e+00 -3.3455700e-01 -8.3278698e-01 2.3006320e+00 2.7641000e-02 -7.0393997e-01 2.2807209e+00 2.8720999e-02 -1.0023850e+00
2.2807209e+00 2.8720999e-02 -1.0023850e+00 2.3961921e+00 -3.2150501e-01 -1.1897759e+00 2.3591161e+00 -3.3455700e-01 -8.3278698e-01
Each file has 9 columns and unknown number of rows.
Each row (consisting of 9 numbers) are just the x,y,z coordinates of the three vertices of a triangle.
I would like to iteratively read in each row and place it in a vector for further manipulations.
I have attempted using fread() to do this. I have searched the internet and the questions on this website, but all of them seem to know the dimensions of their .raw file (row AND column).
Thanks!

Réponse acceptée

dpb
dpb le 10 Juin 2016
fid=fopen(...
while ~feof(fid)
v=cell2mat(textscan(fid,'%f',9,'collectoutput',1));
% do whatever with _v_ here
...
end
fid=fclose(fid);
Alternatively, unless the files are huge, it'll be faster to read the array and process it from memory rather than reading the file record-by-record. (Plus, you may well be able to vectorize the "whatever" and avoid any looping altogether, almost always agoodthing (tm) in Matlab to strive for...
In that case,
fid=fopen(...
a=cell2mat(textscan(fid,'','collectoutput',1));
fid=fclose(fid);
% process the array here...
NB: Two things--first, note that wrapped the textscan call inside cell2mat to return a double array instead of a cell array; when the data are all numeric is much simpler addressing and less overhead. Second, in the second case the use of the empty format string is a flag to textscan that it will return the array in the shape found in the file automagically--you don't need to know either number of records nor items per record as long as it is a regular array.
  1 commentaire
trent
trent le 10 Juin 2016
Thank you for such a clear answer. The file is small enough to process from memory, so I will use the second method.
Thanks!

Connectez-vous pour commenter.

Plus de réponses (0)

Community Treasure Hunt

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

Start Hunting!

Translated by