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?
댓글 수: 0
채택된 답변
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
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
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!