Federico
Federico

Reputation: 1090

How to extract struct element name given part of the name?

I am currently post-processing a lot of .mat files (300+) created with a long simulation (3days+).

Each of these mat files contain several variables, each named after their position on a grid (yes, they've been created with eval).

I thus created a script that opens each of the files sequentially

s = what(pwd);
s = s.mat;

for i=1:length(s)
    data = open(sprintf('%s',s{i,:}));
    % here goes what I would like to do
end

What I am trying to do now is to extract the current name of the data component that fits a certain pattern.

Specifically, I know that in data there is a vector named coef_%i_%i and I would like to isolate it and assign it to a multi-dimensional array.

The second part I know how to do it, I can scan the variable name for the _ characters, isolate the integers and assign the vector to its appropriate location in the array.

My question is:

Upvotes: 0

Views: 146

Answers (1)

matlabgui
matlabgui

Reputation: 5672

Assuming you have something like:

clear data
% create a dummy field
name = sprintf ( 'coef_%i_%i', randi(100,[2 1]) );
% a data struct with a field which starts "coef*"
data.(name) = rand;
% and your data field may contain some other fields?
data.other = [];

You can then extract out the fields which contain the coef string

function output = extractname ( data )
  %extract the fieldnames from data:
  fn = fieldnames(data);

  % find all that have coef in them
  index = cellfun(@isempty, strfind(fn,'coef'));
  % remove any that dont have coef in them
  fn(index) = [];

  %You are then left with one(or more) that contain coef in the name:
  output = fn;
end

If your data struct contains fields which may have "coef" elsewhere in the name you would need to go through them and check if coef is at the start. You should also check that at the end of your function that one and only one field has been found.

Upvotes: 3

Related Questions