Problem Creating Structure Field with For Loop
1 次查看(过去 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?
0 个评论
采纳的回答
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
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.
更多回答(1 个)
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
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
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.)
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Structures 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!