How can I read array from a text file?

조회 수: 11 (최근 30일)
Angel Dimitrov
Angel Dimitrov 2020년 3월 21일
댓글: Angel Dimitrov 2020년 3월 22일
I have a lot of text files in the form:
(0000000000)
(2020231032)
(0222320033)
(3120030223)
(0001132233)
And I want to import them as arrays. When I get rid of the clammers and use dlmread, it reads each row as one big number, but I need them as row vectors of the given length. Is there a way to read the file as the array I wish, or maybe a function that inserts comma after every number?
  댓글 수: 2
Ameer Hamza
Ameer Hamza 2020년 3월 21일
How do you want to load each row into array? Giving an example output based on the lines in question will be helpful
Angel Dimitrov
Angel Dimitrov 2020년 3월 21일
I want to load the whole file as an matrix array, also in this example 5x10 array. I need the output to be:
[0,0,0,0,0,0,0,0,0,0;
2,0,2,0,2,3,1,0,3,2;
0,2,2,2,3,2,0,0,3,3;
3,1,2,0,0,3,0,2,2,3;
0,0,0,1,1,3,2,2,3,3;]

댓글을 달려면 로그인하십시오.

채택된 답변

Ameer Hamza
Ameer Hamza 2020년 3월 21일
편집: Ameer Hamza 2020년 3월 21일
Try this
file = fopen('filename.txt');
data = textscan(file, '(%1d%1d%1d%1d%1d%1d%1d%1d%1d%1d)');
fclose(file);
data = cell2mat(data);
  댓글 수: 3
Ameer Hamza
Ameer Hamza 2020년 3월 22일
Following code will work on arbitrary number of digits
file = fopen('temp.txt');
data = textscan(file, '%s');
fclose(file);
result = cell2mat(cellfun(@(x) sscanf(x(2:end-1), '%1d'), data{1}, 'UniformOutput', 0)')';
Angel Dimitrov
Angel Dimitrov 2020년 3월 22일
Thank you for your help!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Spreadsheets에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by