How can I use "IF" statement to prevent adding same element to an array?

Hello,
So I have a matrix A
A = [ 1 2 3;
2 3 4;
4 5 6]
I create another matrix B where B =[] and the element in B will be added from A. Matrix B becomes
B = [ 1 2;
2 3;
3 1;
2 3;
3 4;
4 2]
The forloop technically go through each row of A to pick the elements for each row of B. B is nx2 matrix. As we can see, "2 3" is repeated. I want to make an If statement that prevent adding existing row in B.
Please help, thank you so much.

 採用された回答

the cyclist
the cyclist 2019 年 11 月 15 日
編集済み: the cyclist 2019 年 11 月 15 日
Would it be acceptable to just remove duplicated rows after-the-fact? If so, you could do
B = unique(B,'rows');
It seems likely that this would be more efficient than checking each row against all prior rows, while B is being constructed.

5 件のコメント

kiet tran
kiet tran 2019 年 11 月 15 日
Thank you for the advice. But I forgot to say that if there is "1 2" I can't have either "1 2" or "2 1". Unique command only remove "1 2" for existing "1 2" in B. Sorry for not being clear in the question.
the cyclist
the cyclist 2019 年 11 月 15 日
Would the following be acceptable?
B = unique(sort(B,2),'row');
This would reduce
[1 2;
2 1]
to just
[1 2]
which seems to be what you want. However, it would also change just
[2 1]
to
[1 2]
even though [1 2] was never present in the first place. Is that OK?
kiet tran
kiet tran 2019 年 11 月 15 日
Thank you for the advice. So the 'sort' command will organize the rows in B to be somewhat the same to the existing ones, and then 'unique' will remove them, right? I tried it in my code and it works perfectly. I will try more different input to see if it holds the goal consistently. Thank you very much !
the cyclist
the cyclist 2019 年 11 月 15 日
I don't know what you mean by "somewhat the same to the existing ones". So, let's be specific.
sort will take each row, and put it in ascending numerical order. Therefore the row [2 1] and the row [1 2] will both become [1 2]. That way, unique keeps only one of those rows.
kiet tran
kiet tran 2019 年 11 月 18 日
Thank you sir, that totally works and very simple and effective.

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

質問済み:

2019 年 11 月 15 日

コメント済み:

2019 年 11 月 18 日

Community Treasure Hunt

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

Start Hunting!

Translated by