Matlab change structure field name by comparing it with a list of conversions
1 view (last 30 days)
Show older comments
Mustahsan Majeed
on 23 Oct 2014
Commented: Geoff Hayes
on 24 Oct 2014
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,
0 Comments
Accepted Answer
Geoff Hayes
on 23 Oct 2014
Edited: Geoff Hayes
on 23 Oct 2014
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
2 Comments
More Answers (0)
See Also
Categories
Find more on Shifting and Sorting Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!