how do you full outer join two structures based on common fields
13 views (last 30 days)
Show older comments
if i have
x = struct()
x.A = 1:4
x.B = 2:5
and
y = struct()
y.A = 4:5
y.C = 1:2
how can i join these to get z such that z looks like:
z.A 1 2 3 4 5
z.B 2 3 4 5 NaN
z.C NaN NaN NaN 1 2
also i'm aware x and y don't need to be structs in this case (but columns A and B have different data types in the real data i'm using). Finally how could this be extended if there were multiple keys? One way i can think of is adding a new column which is the combination of these keys, but is there anything cleaner?
Thanks
0 Comments
Accepted Answer
Guillaume
on 1 Jul 2016
There's nothing in matlab to do that with structures, however the newish table type offers all the join functions you need. For outerjoin there are all the options you need to specify left and right keys.
tx = table([1:4]', [2:5]', 'VariableNames', {'A', 'B'}) %note that the data MUST be in columns
ty = table([4:5]', [1:2]', 'Variablenames', {'A', 'C'})
outerjoin(tx, ty, 'MergeKeys', true)
To convert your structures into table
function t = structofvectortotable(s)
s = structfun(@num2cell, s, 'UniformOutput', false); %convert each vector into cell array
c = struct2cell(s); %convert struct into a cell
t = cell2table(vertcat(c{:})', 'VariableNames', fieldnames(s)); %concatenate cells into one array, transpose into column and convert to table
end
0 Comments
More Answers (0)
See Also
Categories
Find more on Data Type Conversion in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!