set the value of multiple fields in an existing struct

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

回答(1 个)

Rajanya
Rajanya 2024-11-19,10:38
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!

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

产品


版本

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by