Is there a function in MATLAB that can merge two matrices based on column or row labels?

1 view (last 30 days)
For example, I have two data matrices: "data1" and "data2".
data1:
2004070190
20040703100
20040704101
2004070598
data2:
20040702500
20040703495
20040704499
I wish to merge the data into one matrix with unique labels:
output:
20040701900
200407020500
20040703100495
20040704101499
2004070598 0

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 13 Feb 2012
This enhancement has been incorporated by introducing the JOIN function in Statistics Toolbox 7.1 (R2009a). For more information, refer the documentation page and its example from the following documentation page:
<http://www.mathworks.com/help/toolbox/stats/dataset.join.html>
For previous product releases, read below for any possible workarounds:
The following code can accomplish merging two data sets with labels in the first column and arbitrary column size. The resulting merged matrix is padded with zeros for empty entries.
Note: This code is provided as an example only.
function newdat=mergedata(d1,d2)
% MERGEDATA - Function to merge datasets d1, and d2 with unrepeated labels.
% d1 and d2 are matrices where labels are in the first
% column and d1 and d2 can be of different size. Empty entries are padded
% with "0".
% Returns newdat, merged matrix.
newdat=[d1,zeros(length(d1(:,1)),length(d2(1,2:end)))]; %initialize new matrix with zeros
[m,n]=size(newdat); %get dimensions of new matrix
for i=1:length(d2(:,1)) %loop through data to merge
indx=find(newdat(:,1)==d2(i,1)); %find existing dates/labels
if indx
newdat(indx,[n-length(d2(i,2:end))+1:n])=d2(i,2:end); %if label is matched update the row
else
newdat(m+1,[n-length(d2(i,2:end))+1:n])=d2(i,2:end); %if the label is new, create new row
newdat(m+1,1)=d2(i,1); %insert new label in first column
m = m+1; %update the dimension of the new matrix
end
end
newdat=sortrows(newdat); %sort the new matrix
For non-numeric data, this code can be modified to use cell arrays.

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!