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,
댓글 수: 0
채택된 답변
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 Center 및 File Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!