How to brows variable names of a structure and select the closest to a given string?
8 次查看(过去 30 天)
显示 更早的评论
Hi there,
I imported motion capture data to Matlab in the form of a structure.
e.g. Experiment1 file:
data.head_12.time; data.head_12.data
data.arm_4.time; data.arm_4.data
...
Sometimes the index allocated to the marker sets changes between experiments, which results in a change of the variable name in the structure:
e.g. Experiment2 file:
data.head_16.time; data.head_16.data
data.arm_11.time; data.arm_11.data
...
How can I select the closest variable name without knowing the index?
myvariable = find(data.filednames, 'head_xx').data;
3 个评论
Image Analyst
2024-10-18
If you have any more questions, then attach your data files and code to read it in with the paperclip icon after you read this:
采纳的回答
Sameer
2024-10-17
编辑:Sameer
2024-10-17
Hi
To select the closest variable name without knowing the exact index, you can use "dynamic field names" and "regular expressions" to match the desired pattern.
Here's how you can do this:
1. Use "fieldnames()" to get all field names from the structure.
2. Use "regexp()" to find the field name that matches your pattern.
3. Access the data using dynamic field names.
Sample Code :
data.head_12.time = 0:0.1:10; % Sample time data
data.head_12.data = sin(data.head_12.time); % Sample data
data.arm_4.time = 0:0.1:10; % Sample time data
data.arm_4.data = cos(data.arm_4.time); % Sample data
data.leg_7.time = 0:0.1:10; % Sample time data
data.leg_7.data = tan(data.leg_7.time); % Sample data
% Now, let's find the field that matches 'head_xx'
fields = fieldnames(data);
pattern = '^head_\d+$'; % Pattern to match 'head_' followed by digits
matches = regexp(fields, pattern, 'match');
matchedField = fields(~cellfun('isempty', matches));
if ~isempty(matchedField)
selectedField = matchedField{1};
myTime = data.(selectedField).time;
myData = data.(selectedField).data;
disp(['Selected field: ', selectedField]);
disp('Time data:');
disp(myTime);
else
error('No matching field found for pattern: %s', pattern);
end
Please refer to the below MathWorks documentation links:
Hope this helps!
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!