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

8 vues (au cours des 30 derniers jours)
Amit Sarna
Amit Sarna le 1 Juil 2016
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

Réponse acceptée

Guillaume
Guillaume le 1 Juil 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

Plus de réponses (0)

Catégories

En savoir plus sur Data Type Conversion dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by