# How can I check that a newly generated sequence is already in the existing structure list or not?

1 回表示 (過去 30 日間)
Md. Asadujjaman 2020 年 6 月 25 日
コメント済み: Bjorn Gustavsson 2020 年 6 月 28 日
Suppose I have a sequence list as follows:
pp(1).x=[1 2 3 4];
pp(2).x=[3 2 1 4];
pp(3).x=[1 2 3 4];
pp(4).x=[2 1 3 4];
How can I check that a newly generated sequence pp(5).x=randperm(4) is already in the existing structure list 'pop' or not?

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

### 採用された回答

Johannes Fischer 2020 年 6 月 25 日
newPerm = [2 1 3 4];
% this line basically runs over the elements of your struct array and checks whether the array in field 'x' is equal to the new permutation
any(cellfun(@(x) isequal(x, newPerm), {pp(:).x}))
If you want to have all possible permutations of an array you could also use
perms(1:4)
##### 2 件のコメントなしを表示なしを非表示
Md. Asadujjaman 2020 年 6 月 28 日
How can I understand that which number of sequence matches with the new sequence.
Here, 4th sequence of the structure 'pp' matches with the new sequence.
How can get the result (4th sequence) that matches with the new sequence.
Bjorn Gustavsson 2020 年 6 月 28 日
You should use data-structures that makes your programming easy.
In your case I would store the existing permutations in a matrix, ppx, because then something like this would be easier for me to understand:
i_existing = @(newperm) ( ppx(:,1) == newperm(1)) & ( ppx(:,2) == newperm(2)) & ( ppx(:,3) == newperm(3))
which will return an array with 1's and 0'.
Or you could solve it with
find(cellfun(@(x) isequal(x, newPerm), {pp(:).x}))
But then you'll have to check for empty arrays for the case where newPerm doesn't exist.

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

### その他の回答 (1 件)

Bjorn Gustavsson 2020 年 6 月 25 日
For example this can be used:
intersect([1 2 3;1 3 2;2 1 3;2 3 1;3 1 2],[3 2 1],'rows')
%
%ans =
%
% 0x3 empty double matrix
%
intersect([1 2 3;1 3 2;2 1 3;2 3 1;3 1 2],[3 1 2],'rows')
%
%ans =
%
% 3 1 2
Or you can simply check if the minimum Euclidian distance is zero between the new and the existing points:
l_min = min((pop(:,1)-pp.x(1)).^2+(pop(:,2)-pp.x(2)).^2+(pop(:,3)-pp.x(3)).^2+(pop(:,4)-pp.x(4)).^2)
If that is zero the sequence already exists. With the newer matlab-versions you could use the implicit expansion of "+" instead of the
explicit one here. There surely is a large number of ways to do this, others might come up with ways to use strfind (or findstr) or
other variants. You'll have to time these to see which is best for your case.
HTH

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

### カテゴリ

Help Center および File ExchangeStructures についてさらに検索

### Community Treasure Hunt

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

Start Hunting!

Translated by