MATLAB Answers

How to import data with exotic delimiters.

31 views (last 30 days)
Sebastian Faller
Sebastian Faller on 22 Sep 2020 at 11:55
Commented: Stephen Cobeldick on 22 Sep 2020 at 18:23
I have data basicly in a csv file but with ending .lvm looking like
0,000000 4,000000 0,000000 160,645546 39,281321 199,881657
2,439139 4,000000 0,000000 160,569857 39,276997 199,499790
4,879279 4,000000 0,000000 160,491830 39,278343 199,387425
7,326419 4,000000 0,000000 160,322703 39,271629 200,504927
9,748558 4,000000 0,000000 160,229282 39,271306 200,263479
12,180696 4,000000 0,000000 160,125998 39,266773 200,528866
14,625836 4,000000 0,000000 159,913637 39,263853 200,291738
17,061976 4,000000 0,000000 159,628543 39,260609 199,696538
I want an array with each Values.
With python pandas its as easy as:
df = pd.read_csv(file,sep='\t', engine='python',index_col=None, header=None, decimal=',')
But i struggle with Matlab.
Please help me as i have no clue how to search anymore.

  1 Comment

Stephen Cobeldick
Stephen Cobeldick on 22 Sep 2020 at 18:23
Note that readmatrix will handle both the decimal comma and the tab delimiter, and would be by far the best choice for importing this file into MATLAB.

Sign in to comment.

Accepted Answer

Ameer Hamza
Ameer Hamza on 22 Sep 2020 at 12:02
Edited: Ameer Hamza on 22 Sep 2020 at 12:02
Try this
str = fileread('data.txt');
str = strrep(str, ',', '.'); % change , to .
data = textscan(str, '%f\t');
data = reshape(data{1}, 6, []).';
Result
>> data
data =
0 4.0000 0 160.6455 39.2813 199.8817
2.4391 4.0000 0 160.5699 39.2770 199.4998
4.8793 4.0000 0 160.4918 39.2783 199.3874
7.3264 4.0000 0 160.3227 39.2716 200.5049
9.7486 4.0000 0 160.2293 39.2713 200.2635
12.1807 4.0000 0 160.1260 39.2668 200.5289
14.6258 4.0000 0 159.9136 39.2639 200.2917
17.0620 4.0000 0 159.6285 39.2606 199.6965
data.txt file is attached.

More Answers (1)

Stephen Cobeldick
Stephen Cobeldick on 22 Sep 2020 at 18:09
Edited: Stephen Cobeldick on 22 Sep 2020 at 18:22
Using textscan's optional arguments properly avoids awkward reshaping of the output (and you have more flexibility because you can also select which columns you want to import or ignore, their class, etc):
>> str = fileread('data.txt');
>> str = strrep(str,',','.');
>> out = textscan(str,'%f%f%f%f%f%f','Delimiter','\t','CollectOutput',true);
>> out = out{1}
out =
0 4.0000 0 160.6455 39.2813 199.8817
2.4391 4.0000 0 160.5699 39.2770 199.4998
4.8793 4.0000 0 160.4918 39.2783 199.3874
7.3264 4.0000 0 160.3227 39.2716 200.5049
9.7486 4.0000 0 160.2293 39.2713 200.2635
12.1807 4.0000 0 160.1260 39.2668 200.5289
14.6258 4.0000 0 159.9136 39.2639 200.2917
17.0620 4.0000 0 159.6285 39.2606 199.6965

  0 Comments

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!