Add elements of array A to array B and ensure there is no repeated element in B?

4 ビュー (過去 30 日間)
Xiaohan Du
Xiaohan Du 2018 年 7 月 10 日
コメント済み: Xiaohan Du 2018 年 7 月 10 日
Hi all,
If I have arrays A and B, and I'd like to add elements of array A into array B, during this process, B is actively checked to ensure there is no repeated elements in B, how can I do it?
Many thanks!
  2 件のコメント
jonas
jonas 2018 年 7 月 10 日
Can you provide example of A and B with the desired output?
Xiaohan Du
Xiaohan Du 2018 年 7 月 10 日
For example:
A = [2 3 4]; % before adding
B = [5 4 3 1 3]; % add B to A, has to be an iterative check
% because in my code elements of B is generated iteratively,
% not all at once.
A_output = [2 3 4 5 1]; % after adding, no repeated element

サインインしてコメントする。

回答 (2 件)

KSSV
KSSV 2018 年 7 月 10 日
A = rand(10,1) ;
B = rand(10,1) ;
%%check for B
[C,ia,ib] = unique(B) ;
if length(C)==length(B)
fprintf('B has no repeated elements\n') ;
R = A+C ;
else
fprintf('B has repeated elements\n') ;
end
  1 件のコメント
Xiaohan Du
Xiaohan Du 2018 年 7 月 10 日
I meant when adding elements of B into A, check if A has repeated elements. But anyway, this allows to find out if A has repeated elements.
So now there is the problem: if there is repeated element in A, how to remove it and continue to move and check?

サインインしてコメントする。


Guillaume
Guillaume 2018 年 7 月 10 日
B = unique([B, A]); %assuming B and A are row vectors.
If you want to preserve the original ordering of elements:
B = unique([B, A], 'stable');

カテゴリ

Help Center および File ExchangeOperators and Elementary Operations についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by