필터 지우기
필터 지우기

Read numbers from text file with different row sizes into array

조회 수: 3 (최근 30일)
Chak Chan
Chak Chan 2018년 11월 29일
댓글: Sonia Kundu 2021년 8월 3일
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!

답변 (1개)

KSSV
KSSV 2018년 11월 29일
fid = fopen('myfile.txt','r') ;
S = textscan(fid,'%s','delimiter','\n') ;
fclose(fid) ;
S = S{1} ;
  댓글 수: 2
Chak Chan
Chak Chan 2018년 11월 29일
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 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 CenterFile Exchange에서 Data Import and Export에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by