set the value of multiple fields in an existing struct
11 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hello,
I have an existing structure and I would like to update a couple of fields with some new values.
Is there a way to do this without using a for-loop?
% Original struct
OLD = struct('field1',1,'field2',2,'field3',5,'field5',9)
% Struct containing the updates
NEW = struct( 'field2',7,'field3',8)
% Update original with loop
fn_NEW = fieldnames(NEW)
for i = 1:numel(fn_NEW)
OLD.(fn_NEW{i}) = NEW.(fn_NEW{i});
end
0 commentaires
Réponses (1)
Rajanya
le 19 Nov 2024
I understand that you are willing to update the field values in the first structure with the field values in the new structure without the explicit usage of loops.
To achieve this, you can use the ‘intersect’ function of MATLAB to identify the indices where updates need to be done in the former structure and use logical indexing to update the values. The values of both the structures can be extracted as cell arrays using ‘struct2cell’ which will make the manipulation easier.
The below code shows a sample demonstration:
OLD = struct('field1',1,'field2',2,'field3',5,'field5',9);
NEW = struct('field2',7,'field3',8);
fn_NEW = fieldnames(NEW);
fn_OLD = fieldnames(OLD);
[~, idxInOld, idxInNew] = intersect(fn_OLD, fn_NEW);
oldValues = struct2cell(OLD);
newValues = struct2cell(NEW);
oldValues(idxInOld) = newValues(idxInNew);
updatedStruct = cell2struct(oldValues, oldFields)
If you would like to explore more about ‘intersect’, ‘struct2cell’ or 'cell2struct', you may refer to their documentation pages by entering the following commands in the MATLAB Command Window:
doc intersect
doc struct2cell
doc cell2struct
Hope this helps!
0 commentaires
Voir également
Catégories
En savoir plus sur Structures dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!