Find the common elements in same indices in two arrays.

조회 수: 11 (최근 30일)
Md. Asadujjaman
Md. Asadujjaman 2022년 4월 6일
댓글: Voss 2022년 4월 6일
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
Voss
Voss 2022년 4월 6일
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));

댓글을 달려면 로그인하십시오.

채택된 답변

Davide Masiello
Davide Masiello 2022년 4월 6일
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 ]

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by