Azzera filtri
Azzera filtri

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

2 visualizzazioni (ultimi 30 giorni)
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?

Risposta accettata

Johannes Fischer
Johannes Fischer il 25 Giu 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 Commenti
Md. Asadujjaman
Md. Asadujjaman il 28 Giu 2020
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 il 28 Giu 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.

Accedi per commentare.

Più risposte (1)

Bjorn Gustavsson
Bjorn Gustavsson il 25 Giu 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

Categorie

Scopri di più su Structures in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by