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

13 ビュー (過去 30 日間)
Amit Sarna
Amit Sarna 2016 年 7 月 1 日
回答済み: Guillaume 2016 年 7 月 1 日
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 Center および File ExchangeData Type Conversion についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by