Matlab change structure field name by comparing it with a list of conversions
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Mustahsan Majeed
am 23 Okt. 2014
Kommentiert: Geoff Hayes
am 24 Okt. 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 Kommentare
Akzeptierte Antwort
Geoff Hayes
am 23 Okt. 2014
Bearbeitet: Geoff Hayes
am 23 Okt. 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 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Shifting and Sorting Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!