How do I merge vectors?

1 次查看(过去 30 天)
I have a 10X1 vector A=[1;3;7;10;12;14;15;18;20;21] and a 10X1 vector B=[3;12;15;18;20;0;0;0;0;0]. Is there a way to come up with a 10X2 vector C such that the equal elements in each vector sit at the same row in vector C? I want to retain all elements of vector A in vector C and keep only the elements from vector B that have values equal to the one elements in vector A. Ideally, My final vector C would look something like this: C=[1 0;3 3;7 0;10 0;12 12;14 0;15 15;18 18;20 20;21 0]. Any thoughts?

采纳的回答

Star Strider
Star Strider 2015-12-29
The intersect function works best here:
A=[1;3;7;10;12;14;15;18;20;21];
B=[3;12;15;18;20;0;0;0;0;0];
[m,ia,ib] = intersect(A, B, 'stable');
C = [A zeros(size(A,1),1)];
C(ia,2) = B(ib)
C =
1 0
3 3
7 0
10 0
12 12
14 0
15 15
18 18
20 20
21 0

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by