Dimensioning a field within a structure array for reading data
이전 댓글 표시
I am reading a file that contains a number of groups of fields and I'm trying to figure out how to do this.
I'd like to create structure (CTW) where I will group the data, but I'm running into problems defining and allocating the fields.
The first set of data in the file is an array of four variables of 8 characters each. I want to call these c8(1), through c8(4).
The second set of data in the file is 6 variables of 20 characters each. I want to call these c20(1), through c20(6).
Currently, my code looks like this:
fid = fopen(filename, 'r');
for x = 1 : 4
CTW.c8(x) = string(fread(fid, 8, '*char')');
end
for x = 1 : 6
CTW.c20(x) = string(fread(fid, 20, '*char')');
end
Matlab gives the following error:
Unable to perform assignment because the indices on the left side are not compatible with the size of the right side.
I know that I can read in the individual strings and then create the structure, like this:
c81 = string(fread(fid, 8, '*char')');
c82 = string(fread(fid, 8, '*char')');
c83 = string(fread(fid, 8, '*char')');
c84 = string(fread(fid, 8, '*char')');
CTW.c8 = [c81, c82, c83, c84];
clear c81 c82 c83 c84
end
but that seems inelegant. What is the best way to do this? Is there some way to pre-allocate the arrays within the structure?
채택된 답변
추가 답변 (1개)
Walter Roberson
2025년 8월 15일
0 개 추천
Your loop code has a problem when you reach end of file. In such a case, fread() returns empty, and string(empty) returns a 0 x 0 string, which cannot be stored in a 1 x 1 destination.
카테고리
도움말 센터 및 File Exchange에서 Whos에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!