How can I check that a newly generated sequence is already in the existing structure list or not?
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Md. Asadujjaman
le 25 Juin 2020
Commenté : Bjorn Gustavsson
le 28 Juin 2020
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 commentaires
Réponse acceptée
Johannes Fischer
le 25 Juin 2020
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 commentaires
Bjorn Gustavsson
le 28 Juin 2020
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.
Plus de réponses (1)
Bjorn Gustavsson
le 25 Juin 2020
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 commentaires
Voir également
Catégories
En savoir plus sur Data Types dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!