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

1 visualizzazione (ultimi 30 giorni)
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!

Risposta accettata

dpb
dpb il 21 Ago 2014
Modificato: dpb il 21 Ago 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.

Più risposte (0)

Categorie

Scopri di più su Data Import and Export in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by