Problem Creating Structure Field with For Loop

2 次查看(过去 30 天)
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?

采纳的回答

Jonas
Jonas 2022-5-7
编辑:Jonas 2022-5-7
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 个评论
Jonas
Jonas 2022-5-7
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 2022-5-7
Thank you! I cleared my variables, and everything works correctly.

请先登录,再进行评论。

更多回答(1 个)

Steven Lord
Steven Lord 2022-5-7
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.)

类别

Help CenterFile Exchange 中查找有关 Whos 的更多信息

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by