Find the common elements in same indices in two arrays.

9 vues (au cours des 30 derniers jours)
Md. Asadujjaman
Md. Asadujjaman le 6 Avr 2022
Commenté : Voss le 6 Avr 2022
Suppose,
A = [1001 1002 1003 2001 2002 1004 1005 2003 2004 2005]
B = [1001 1002 2001 2002 1003 1004 2003 1005 2004 2005]
X and Y are two arrays with zero elements
X = [0 0 0 0 0 0 0 0 0 0]
Y = [0 0 0 0 0 0 0 0 0 0]
(1) Now I want to find the common elements that are in the same indices of A and B and put in X and Y.
Answer will be:
X = [1001 1002 0 0 0 0 1004 0 2004 2005]
Y = [1001 1002 0 0 0 0 1004 0 2004 2005]
(2) Now generate two random indices; e.g., 5 and 7
Now, I want to replace the elements of X and Y between the random indices (5 and 7) with the elements of A and B, respectively.
Answer will be:
X = [1001 1002 0 0 2002 1004 1005 0 2004 2005]
Y = [1001 1002 0 0 1003 1004 2003 0 2004 2005]
(3) Now I want to replace the zero elements of X with the elements of B (that are not in X; i.e., 2001, 1003 and 2003), following the same relative order of the elements.
Also, I want to replace the zero elements of Y with the elements of A (that are not in Y; i.e., 2001, 2002 and 1005), following the same relative order of the elements.
Answer will be:
X = [1001 1002 2001 1003 2002 1004 1005 2003 2004 2005]
Y = [1001 1002 2001 2002 1003 1004 2003 1005 2004 2005]
How can I do these? Thanks in advance.
  1 commentaire
Voss
Voss le 6 Avr 2022
You can use randi to generate random indices, e.g.:
% generate two integers between 1 and numel(X) - the number of elements of
% X - and sort them so that rand_idx(2) >= rand_idx(1) so you can do
% indexing like: X(rand_idx(1):rand_idx(2))
rand_idx = sort(randi(numel(X),1,2));

Connectez-vous pour commenter.

Réponse acceptée

Davide Masiello
Davide Masiello le 6 Avr 2022
clear,clc
A = [1001 1002 1003 2001 2002 1004 1005 2003 2004 2005];
B = [1001 1002 2001 2002 1003 1004 2003 1005 2004 2005];
X = zeros(size(A));
X(A == B) = A(A == B);
Y = X;
rand_idx = [5,7];
X(rand_idx) = A(rand_idx);
Y(rand_idx) = B(rand_idx);
X(X == 0) = B(X == 0);
Y(Y == 0) = A(Y == 0);
fprintf(['X = [',repmat('%d ',size(X)),']'],X)
X = [1001 1002 2001 2002 2002 1004 1005 1005 2004 2005 ]
fprintf(['Y = [',repmat('%d ',size(Y)),']'],Y)
Y = [1001 1002 1003 2001 1003 1004 2003 2003 2004 2005 ]

Plus de réponses (0)

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by