MATLAB: Matlab change structure field name by comparing it with a list of conversions

change name in a loopfieldnamerename

Hello,
I want to code something which can do the following:
I have a file named 'labellist.mat' which has 2 columns and in column 1 all the names I want to replace are in and in column 2 all the new names which I want to replace with are in. So I wanna make a loop to check if the a name is in column 1, if yes replace it with the name in column 2. The fieldnames I want to replace are in a struct.
if fieldname is in the 'labellist.mat' column 1'
replace that fieldname with 'labellist.mat' column 2.
I hope I was able to explain my question correctly.
Thanks,

Best Answer

Mustahsan - to be clear, you have a struct with a number of fields. If any of those field names appear in column 1 of your labellist.mat file, then you want to replace that field name with that in column 2. Is that is correct, then you can try the following. Suppose you have a cell array of field names and their replacements (read from your file) as
namesArray = {'fieldA' 'fieldANew' ; 'fieldB' 'fieldBNew' ; 'fieldC' 'fieldCNew'};
and a struct like
myStruct = struct('fieldA',0,'fieldB',1,'fieldD',42);
where
myStruct =
fieldA: 0
fieldB: 1
fieldD: 42
We can then create a list of the fields in the structure, iterate over each one and replace where necessary
structFields = fields(myStruct);
for k=1:length(structFields)
fieldName = structFields{k};
% find the index of this field name in the first column of namesArray
idx = find(strcmp(namesArray(:,1),fieldName));
if ~isempty(idx)
% field name exists so get the replacement
newFieldName = namesArray{idx,2};
% create the new field
myStruct.(newFieldName) = myStruct.(fieldName);
% remove the old field name
myStruct = rmfield(myStruct,fieldName);
end
end
And the field names in myStruct are replaced
myStruct =
fieldD: 42
fieldANew: 0
fieldBNew: 1