How to read and take a part of data of a text file in MATLAB?

8 vues (au cours des 30 derniers jours)
Phan
Phan le 21 Août 2014
Modifié(e) : dpb le 21 Août 2014
Dear everyone,
Please help me to solve this problem. I need to make a code that can read data from a text file. The format of the file is as follows:
0.1 ABC63-820
0.2 S815
...
1.0 EG813
I want to take out three arrays.
One is the first column: X=[0.1 0.2 ... 1.0].
Another one is the last two digits of the second column: Y=[20 15 ... 13].
The last one is the rest of the second column: Z=[ABC63-8 S8 ... EG8].
Can anyone help me to write a code to take out these data?
Thank you so much!
  2 commentaires
Phan
Phan le 21 Août 2014
The difference is that the strings are now arbitrary. They are not a fixed value any more.

Connectez-vous pour commenter.

Réponse acceptée

dpb
dpb le 21 Août 2014
Modifié(e) : dpb le 21 Août 2014
For a file with your three rows above...
>> fid=fopen('phan.dat');
>> c=textscan(fid,'%f %s','delimiter',' ')
c =
[3x1 double] {3x1 cell}
>> d=cell2mat(c(:,1));
>> for i=1:length(c{2})
s=deblank(char(c{2}(i)));
d(i,2)=str2num(s(end-1:end));
ss(i,1)={s(1:end-2)};
end
>> d
d =
0.1000 20.0000
0.2000 15.0000
1.0000 13.0000
>> ss
ss =
'ABC63-8'
'S8'
'EG8'
>>
Couldn't think of a neater way to get the two end characters of a variable-length cellstr...can't do triple-level indexing so did the conversion to character string and deblank to be able to get the two end character positions.
Preallocate first for real file, of course...
ADDENDUM
I figured out where I fouled up the anonymous function to convert the last two digits and get the strings via cellfun
y=cell2mat(cellfun(@(x) str2num(x(end-1:end)),c{2},'uniform',0));
z=cellfun(@(x) x(1:end-2),c{2},'uniform',0);
with the original request for different arrays for the three results.
How overall time will compare w/ two scannings via cellfun vis a vis one loop for larger files I don't know and didn't test.
  1 commentaire
Phan
Phan le 21 Août 2014
Thank you so much for your help! You are my savior!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Data Import and Export dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by