过滤出矢量中三对的组合。一种更简约的方式?

时间:2016-03-10 13:41:53

标签: python r matlab permutation

我试图找到一种更好的方法来过滤很少的情况,即在三对矢量的置换过程中发生三个连续的对。这是我的代码。这是用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

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

您可以轻松地使用索引与isequal结合来检查此内容。

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

这只是检查每个元素是否与成对意义上的元素不等。