Read textfile seperated by ':' and put it in a table

2 ビュー (過去 30 日間)
pdefesche
pdefesche 2015 年 10 月 19 日
回答済み: pdefesche 2015 年 10 月 21 日
Hi,
I have some data which i would like to use in Matlab. the following file is an example:
% test.txt
!Drawing Name: 1234567 Drawing File: 1234567_0
%Section 1: Header info
1234567:00:19/10/2015::::AB::::CD::::KL
%Section 2: data
1:2:3:4:5:6:7:8::::::::::::::::::::::::::900
%End of File Marker
I want to place this data into a table which makes a new column if ':' and makes a new row if 'CR LF' (enter). The data can always change in length, so section 1 can have 10 delimiters(':') and section 2 can have for example 30 delimiters(':'),
Can someone point me in the right direction or give me some example code? I've tried some functions, but without succes. So far the only function working for me is:
% code
h = fileread('test.txt');
Thanks in advance.
Regards,
pdefesche

採用された回答

TastyPastry
TastyPastry 2015 年 10 月 19 日
Use strsplit() with the delimiter ':'. It doesn't care how many colons are in a row. All the data will be put into a cell array of strings, so you'll need to modify the data type using str2double() if you want to use it for calculations.
  3 件のコメント
Guillaume
Guillaume 2015 年 10 月 20 日
fileread preserves the line returns when it reads a text file. What it does not do it line ending normalisation, so depending on the source of the file, the line ending is either going to be '\r\n' or '\n'. Nonetheless, you can still also use strsplit t separate the lines. You need to do that before the colon separation:
lines = strsplit(fileread('somefile.txt'), {'\r\n', '\n'});
%note the order of the split strings needs to be in that order
%to make sure '\r\n' takes precedence.
splitlines = cellfun(@(l) strsplit(l, ':'), lines, 'UniformOutput', false);
pdefesche
pdefesche 2015 年 10 月 20 日
Thanks guillaume! Works, case solved :)

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

その他の回答 (1 件)

pdefesche
pdefesche 2015 年 10 月 21 日
One more question:
is it possible to now visually show the data in a table? When i open the splitted data i see arrays of cells.
I've tried the following:
% code
mtable = uitable(gcf,'Data',transposedsplitlines);
but returns following error:
Error using uitable Values within a cell array must be numeric, logical, or char

カテゴリ

Help Center および File ExchangeText Files についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by