- The first column contains all elements from vector A.
- The second column contains the elements from vector B, but only those that have corresponding matches in A and in the same position.
How do I merge vectors?
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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?
0 Kommentare
Antworten (1)
BhaTTa
am 26 Jul. 2024
To achieve this, you want to create a 10×2 matrix C where:
You can accomplish this by iterating over the elements of vector A and finding the corresponding matches in vector B. Here's how you can do it in MATLAB:
% Define the input vectors
A = [1; 3; 7; 10; 12; 14; 15; 18; 20; 21];
B = [3; 12; 15; 18; 20; 0; 0; 0; 0; 0];
% Initialize the output matrix C
C = zeros(length(A), 2);
% Fill the first column of C with elements from A
C(:, 1) = A;
% Loop through each element in A to find matches in B
for i = 1:length(A)
% Find the index of A(i) in B
index = find(B == A(i));
% If a match is found, place it in the second column of C
if ~isempty(index)
C(i, 2) = B(index(1));
else
% If no match is found, ensure the second column is zero
C(i, 2) = 0;
end
end
% Display the result
disp(C);
0 Kommentare
Siehe auch
Kategorien
Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!