How to read array from a text file into each row of a matrix.

조회 수: 3 (최근 30일)
Raghav Rathi
Raghav Rathi 2022년 2월 26일
답변: Scott MacKenzie 2022년 2월 26일
Hi,
I am trying to read a text file which contains arrays in each line. I am trying to read each line into new row of a matrix.
The text file is in the following format.
[255, 255, 0, 0, 11, 0, 1, 0, 11, 11, 11, 11, 11, 11]
[255, 255, 0, 0, 18, 0, 1, 0, 18, 18, 18, 18, 18, 18]
[255, 255, 0, 0, 12, 0, 1, 0, 12, 12, 12, 12, 12, 12]
[255, 255, 0, 0, 10, 0, 1, 9, 10, 218, 10, 138, 10, 58]
[255, 255, 0, 0, 4, 0, 1, 0, 4, 4, 4, 4, 4, 4]
.
.
.
I tried to do it using readmatrix but I am getting the following error.
Error using readmatrix (line 158)
Unable to find or open file. Check the path and
filename or file permissions.
Error in decodePyramid (line 9)
crc_ = readmatrix(dir+pktFile);
Any help is appreciated.
Thank you.
  댓글 수: 5
Raghav Rathi
Raghav Rathi 2022년 2월 26일
Thanks Scott, It kind of works but It is also cutting the first and last element.
NaN 255 0 0 6 0 1 0 6 6 6 6 6 NaN
Can you help me with fixing that?
Raghav Rathi
Raghav Rathi 2022년 2월 26일
if you look at the text file, each line contains 14 elements
[255, 255, 0, 0, 6, 0, 1, 0, 6, 6, 6, 6, 6, 6]
But they way you mentioned is skipping the first and last elements.
NaN should be the '[' and ']' but there is a 225 and 6 missing as well.

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

답변 (2개)

Voss
Voss 2022년 2월 26일
fid = fopen('input.txt');
data = str2num(fread(fid,'*char').');
fclose(fid);
disp(data);
255 255 0 0 11 0 1 0 11 11 11 11 11 11 255 255 0 0 18 0 1 0 18 18 18 18 18 18 255 255 0 0 12 0 1 0 12 12 12 12 12 12 255 255 0 0 10 0 1 9 10 218 10 138 10 58 255 255 0 0 4 0 1 0 4 4 4 4 4 4

Scott MacKenzie
Scott MacKenzie 2022년 2월 26일
OK, this should work. First, combine dir and pktFile using the fullfile function. Read the data using readtable, then restore the 1st and last columns to numeric values (by removing the brackets and converting to double). If you want the data in a plain matrix, follow with table2array:
T = readtable(fullfile(dir, pktFile));
T.Var1 = cellfun(@(x) str2double(x), erase(T.Var1, '['));
T.Var14 = cellfun(@(x) str2double(x), erase(T.Var14, ']'));
crc_ = table2array(T);

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by