joining two matrices by column 1
2 次查看(过去 30 天)
显示 更早的评论
How can I combine two matrices, say:
a = [29 315; 41 64; 42 130]
b = [29 260; 39 171; 41 430]
I need the following:
c = [29 315 260; 39 0 171; 41 64 430; 42 130 0]
Combine the first column from a and b to form the first column in c (no repeated values). Then add the corresponding second columns from a and b to the second and third in c (zero if no match).
I need to do this for a large dataset. I have no idea how to proceed.
1 个评论
Bob Thompson
2018-9-28
I would suggest initializing an array of 0s first, just to make sure you don't have any uneven indices. I don't entirely know how to write the rest of it, but my guess would be some kind of loop, a few if statements, and using the isunique() logic to reduce any duplicate inputs.
采纳的回答
James Tursa
2018-9-28
A simplistic approach assuming 1st column numbers are sorted and do not repeat within each a and b variable:
c = unique([a(:,1);b(:,1)]);
c(ismember(c(:,1),b(:,1)),3) = b(:,2);
c(ismember(c(:,1),a(:,1)),2) = a(:,2);
If the simplistic assumptions above are not correct, then you would have to add code for sorting etc.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!