Error creating structure field names with a for loop
조회 수: 5 (최근 30일)
이전 댓글 표시
I have several directories that each contain multiple .txt0 files that I am trying to process. (For the sake of this question, these .txt0 files are empty files because I'm only concerned with a problem concerning the file names.) Each file in my directories contains one of the following character strings:
id = ["RS","LS" "OC" "RR" "RL" "LR" "LL" ...
"1A" "2A" "3A" "4A" "5A" "6A" "7A" "8A" "9A"...
"1B" "2B" "3B" "4B" "5B" "6B" "7B" "8B" "9B"...
"1C" "2C" "3C" "4C" "5C" "6C" "7C" "8C" "9C"]';
I would like to create a separate field in a structure named "data" for each .txt0 file in each directory. So, in one directory I have three .txt0 files - 1A.txt0, 3B.txt0, 9C.txt0. I would like to programmatically create three fields in the structure "data" (so, data.1A, data.3B, data.9C). I have tried the following script
data{1}.files = dir(fullfile(pwd,'*.txt0'));
id = ["RS","LS" "OC" "RR" "RL" "LR" "LL" ...
"1A" "2A" "3A" "4A" "5A" "6A" "7A" "8A" "9A"...
"1B" "2B" "3B" "4B" "5B" "6B" "7B" "8B" "9B"...
"1C" "2C" "3C" "4C" "5C" "6C" "7C" "8C" "9C"]';
for j = 1:length(data{1}.files)
data_vel{1}.file_name{j,1} = data_vel{1}.velocity_files(j).name;
data_vel{1}.(data_vel{1}.file_name{j})
end
which produces the following error:
Unrecognized field name "1A.txt0".
My script finds the files okay:
>> data{1}.files
ans =
3×1 struct array with fields:
name
folder
date
bytes
isdir
datenum
I have no idea what is wrong with my script. Can someone please help?
댓글 수: 1
Stephen23
2022년 7월 1일
편집: Stephen23
2022년 7월 1일
"I have no idea what is wrong with my script. "
You are forcing (meta-)data into fieldnames, which as you have found out is fragile/buggy and inefficient.
Much better approach: store (meta-)data as data in its own right, in a variable/field/.... This you can do simply and easily in an array using simple and efficient indexing, for example indexing into a structure array:
S(1).data = ..
S(1).name = ..
S(2).data = ..
S(2).name =
etc.
채택된 답변
Steven Lord
2022년 6월 30일
The first character of a struct field name must be a letter. Later characters can be digits, but not the first one.
You could simply append a letter to the beginning of each file's name when assigning and when retrieving the struct field. Or if the file names could contain other characters not allowed in a struct field name (allowed characters are letters, digits, and the underscore character) use matlab.lang.makeValidName to ensure they are valid struct field names.
추가 답변 (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!