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!