How to brows variable names of a structure and select the closest to a given string?
8 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Image Analyst
el 18 de Oct. de 2024
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:
Respuesta aceptada
Sameer
el 17 de Oct. de 2024
Editada: Sameer
el 17 de Oct. de 2024
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!
Más respuestas (0)
Ver también
Categorías
Más información sobre Characters and Strings en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!