Read numbers from text file with different row sizes into array

2 Ansichten (letzte 30 Tage)
Chak Chan
Chak Chan am 29 Nov. 2018
Kommentiert: Sonia Kundu am 3 Aug. 2021
I have a text file called mesh.txt which contains integers in a format like this:
33
18 48
34 37
49 27
66 32
78 27
92 34
111 51
30 62
49 69
83 69
100 61
14 6
2 46
18 82
41 83
94 83
122 81
126 50
118 7
34 8
67 7
100 8
66 84
37 49
50 47
65 48
79 48
93 49
37 49
50 47
65 48
79 48
93 49
42
12 13 1
12 1 2
20 12 2
20 2 3
21 20 3
3 4 21
4 5 21
22 21 5
6 22 5
That being said, some rows have different size than the others. I looked up some similar questions but it seems most of them have neat text files in which the row size is always the same. How do I read integers from each row and store them all in the same array? In other words, I want the output to be double array that looks like:
[[33],
[18,48],
[34,37],
...
[42],
[12,13,1],
...
[6,22,5]]
It'd be great if they are all stored in an array/cell array. But storing data in different cells depending on size is acceptable as well since they actually have different meaning. Thanks!

Antworten (1)

KSSV
KSSV am 29 Nov. 2018
fid = fopen('myfile.txt','r') ;
S = textscan(fid,'%s','delimiter','\n') ;
fclose(fid) ;
S = S{1} ;
  2 Kommentare
Chak Chan
Chak Chan am 29 Nov. 2018
This method concatenates numbers in the same row into one big number. For example the second row now becomes 1848 rather than [18,48]
Sonia Kundu
Sonia Kundu am 3 Aug. 2021
Hi @Chak Chan, Did you get the answer for this problem, I am facing the same issue, rows from the file are getting stored as a string like '18,48' rather than [18,48]. when I apply union on this cell array it always gives values between 0-9 as it contatenates numbers in the same row. Thanks

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Low-Level File I/O finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by