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

2 ビュー (過去 30 日間)
Phan
Phan 2014 年 8 月 21 日
編集済み: dpb 2014 年 8 月 21 日
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 件のコメント
Phan
Phan 2014 年 8 月 21 日
The difference is that the strings are now arbitrary. They are not a fixed value any more.

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

採用された回答

dpb
dpb 2014 年 8 月 21 日
編集済み: dpb 2014 年 8 月 21 日
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 件のコメント
Phan
Phan 2014 年 8 月 21 日
Thank you so much for your help! You are my savior!

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by