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

1 次查看(过去 30 天)
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 个评论
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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by