set the value of multiple fields in an existing struct
1 回表示 (過去 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
0 件のコメント
回答 (1 件)
Rajanya
2024 年 11 月 19 日
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 件のコメント
参考
カテゴリ
Help Center および File Exchange で Structures についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!