How can i merge 2 cells with different items

3 views (last 30 days)
I need to merge 2 cells with different items like:
str1.item_a = 5;
str1.item_b = 4;
str1.item_c = zeros(1,5);
str2.item_d = 0.5;
str2.item_e = 41;
Result:
str3.item_a = 5;
str3.item_b = 4;
str3.item_c = zeros(1,5);
str3.item_d = 0.5;
str3.item_e = 41;
Thanks

Accepted Answer

Jeff Miller
Jeff Miller on 23 Sep 2019
function str3 = mergefields(str1,str2)
% Note: Returns the value in str2 for any field that is common
% to both str1 & str2.
str3 = str1;
fields2 = fieldnames(str2);
for i=1:numel(fields2)
str3.(fields2{i}) = str2.(fields2{i})
end
end

More Answers (1)

the cyclist
the cyclist on 20 Sep 2019
I would solve this by trying to use different MATLAB data types more effectively:
str(1).item = {5,4,zeros(1,5)};
str(2).item = {0.5,41};
str(3).item = [str(1).item str(2).item];
Note that the field item is a cell array.
  1 Comment
Riccardo Micci
Riccardo Micci on 23 Sep 2019
Unfortunately i can't do that since the 2 input structures are beyond my control

Sign in to comment.

Categories

Find more on Get Started with MATLAB in Help Center and File Exchange

Products


Release

R2018a

Community Treasure Hunt

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

Start Hunting!