Problem Creating Structure Field with For Loop

1 view (last 30 days)
I'm having trouble creating and populating a structure field using a for loop. What I've attempted is
for j = 1:6
structure{1}.file_name_string(j) = strcat('file_name_',num2str(j));
end
which yields
Unable to perform assignment because the indices on the left side are not compatible with the size of the right side.
When I try
for j = 1:length(velocity_raw{1}.velocity_files)
strcat('file_name_',num2str(j))
end
I get the entries that I want, but they aren't assigned to the structure field.
I don't understand what the error message means, and I don't understand how to fix the problem. I expect that my problem is basic, but I just haven't been able to figure it out. Can someone please help?

Accepted Answer

Jonas
Jonas on 7 May 2022
Edited: Jonas on 7 May 2022
struct are indexed with round brackets, after that use {} if the structure field file_name_string shall be a cell
for j = 1:6
structure(1).file_name_string{j} = strcat('file_name_',num2str(j));
end
this gives you a 1x1 struct with a field which is a cell array of length 6
if you want a 1x6 struct with a field which is ancharacter array, use
for j = 1:6
structure(j).file_name_string = strcat('file_name_',num2str(j));
end
  3 Comments
Jonas
Jonas on 7 May 2022
i dont know, maybe you created a weird variable in your workspace. please type
clear
and try the code again, i have no problems running the code.
Allen Hammack
Allen Hammack on 7 May 2022
Thank you! I cleared my variables, and everything works correctly.

Sign in to comment.

More Answers (1)

Steven Lord
Steven Lord on 7 May 2022
Do you want the names of the fields in the struct array to be file_name_ followed by a number (file_name_1, file_name_2, etc.)?
s = struct;
for k = 1:5
fn = "file_name_" + k;
s.(fn) = k.^2;
end
s
s = struct with fields:
file_name_1: 1 file_name_2: 4 file_name_3: 9 file_name_4: 16 file_name_5: 25
Or do you want to use actual file names as the field names (something like myImageFile1, myTextFile2, etc.?)
t = struct;
files = {'census.mat', 'eight.tif'};
for k = 1:length(files)
fn = matlab.lang.makeValidName(files{k}); % since field names can't contain periods
t.(fn) = k.^2;
end
t
t = struct with fields:
census_mat: 1 eight_tif: 4
Or do you want to do something else? If so please provide a small concrete example of what you want to do (don't worry about how to create the struct using code, just explain in words.)

Categories

Find more on Structures in Help Center and File Exchange

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!