Dimensioning a field within a structure array for reading data
Show older comments
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 Comment
Jim McIntyre
on 18 Aug 2025
Accepted Answer
More Answers (1)
Walter Roberson
on 15 Aug 2025
0 votes
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.
1 Comment
Jim McIntyre
on 18 Aug 2025
Categories
Find more on Whos in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!