Error creating structure field names with a for loop
4 views (last 30 days)
Show older comments
Allen Hammack
on 30 Jun 2022
Commented: Allen Hammack
on 28 Jul 2022
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 Comment
Stephen23
on 1 Jul 2022
Edited: Stephen23
on 1 Jul 2022
"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.
Accepted Answer
Steven Lord
on 30 Jun 2022
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.
More Answers (0)
See Also
Categories
Find more on Structures in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!