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

조회 수: 2 (최근 30일)
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
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
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
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
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 CenterFile Exchange에서 Structures에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by