过滤出向量中三对的组合。更节省的方式?

2024-07-03 07:15:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图找到一个更好的方法来过滤掉一个罕见的情况,即在一个由三对向量组成的排列过程中,出现了三对连续的向量。这是我的密码。这是用Matlab编写的,但我想它也适用于其他任何东西,比如Python或R

    %// randomize 6-sequence of 3 pitches
    %// This loop makes sure that in each sequence the two conditions are
    %// met:
    %// i.  each syllable/speaker occured at least twice,
    %// ii. changes btw. 2 consec. syl/spk occured 2 and 3 times within 
    %//     one sequence.
    ok = 0;
    while ~ok
        %// Randomly permute sequence.
        Itmp2 = [1 1 2 2 3 3];
        tmp = randperm(6);
        Itmp2 = Itmp2(tmp);

        %// Calculate difference between the next and current neighbor to
        %// check for consecutive (i.e. zeros) and non-consecutive 
        %// presentations (i.e. non-zeros).            
        d = diff(Itmp2);           
        %// Check to see if cond ii is met by finding at least 2
        %// non-consecutive presentations AND no more than 3. If found
        %// set the while escape flag to 1.
        if (length(find(d~=0)) >= 2 && length(find(d~=0)) <= 3) % war vorher 4
            ok = 1;
        end

        %// But wait! We didn't fullfill condition i, so we can't exit
        %// the while loop just yet! Check it with this if statement.
        %// If two or more zeros are present in d, convolution gives for
        %// second+ zero a 2 and max(vector) = 2 which == 2, thus enters
        %// if statement, and while loop continues. Hmm, but when is it
        %// not fullfilled? When the randperm provides three consecutive
        %// pairs, and this should only happen 6 times, since we have 3
        %// pairs that can be permuted. Thus 3! = 6 out of 6! = 720.
        if ok == 1
            if max(conv(double(d==0), double([1 1]))) == 2
                ok = 0;
                sprintf('bam')
            end
        end

Tags: andofthetoloopifzerosok
2条回答

您可以简单地使用索引和isequal来检查这一点。你知道吗

ok = ~isequal(Itmp2(1:2:end), Itmp2(2:2:end))

这只是检查每个元素在成对意义上是否不等于它后面的元素。你知道吗

基本上,您要防止3个不同坐标从其右侧具有相同值的情况。 以下条件将起作用:

ok = sum(conv(Itmp2,[1 -1],'same')==0)~=3

相关问题 更多 >