필터 지우기
필터 지우기

Problem Creating Structure Field with For Loop

조회 수: 1 (최근 30일)
Allen Hammack
Allen Hammack 2022년 5월 7일
댓글: Allen Hammack 2022년 5월 7일
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에서 Structures에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by