Error creating structure field names with a for loop

7 次查看(过去 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
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
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.
  1 个评论
Allen Hammack
Allen Hammack 2022-7-28
Thank you for that insight! I've changed the structure field names, and everything is working for me now!

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by