Read numbers from text file with different row sizes into array
2 次查看(过去 30 天)
显示 更早的评论
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!
0 个评论
回答(1 个)
KSSV
2018-11-29
fid = fopen('myfile.txt','r') ;
S = textscan(fid,'%s','delimiter','\n') ;
fclose(fid) ;
S = S{1} ;
2 个评论
Sonia Kundu
2021-8-3
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
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!