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!