how do you full outer join two structures based on common fields
조회 수: 13 (최근 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
댓글 수: 0
채택된 답변
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
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Data Type Conversion에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!