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

1 次查看(过去 30 天)
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,

采纳的回答

Geoff Hayes
Geoff Hayes 2014-10-23
编辑:Geoff Hayes 2014-10-23
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by