How to read and take a part of data of a text file in MATLAB?
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!