how do you full outer join two structures based on common fields

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

采纳的回答

Guillaume
Guillaume 2016-7-1
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 个)

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by