How can I generate a binary pattern in MATLAB that represents a Euclidean rhythm?

I want to generate a Euclidean rhythm in Matlab as a sequence of 1s and 0s, but I don't know how to start.

So I know that I have a variable a = the amount of 1s, b = the length c = the amount of 0s So that would give a = a (you can choose a number), b = b (you can choose a number) and c = b-a For the rhythm I want to have all the 1s divided as evenly as possible throughout the 0s (Bjorklund's algorithm).

As an example: b = 13 and a = 5

So it might be good to put every 1 together with a 0, that would be:

01 01 01 01 01 000

Now you have three 0s and five pairs of 01s.

Now to divide 0 evenly with the pairs:

010 010 010 0101

Now to divide the two 01s evenly into the three 010s

0100101001010

This is as evenly we can distribute five 1s over the length of 13. Right now I want to create a script in matlab which give you a rhythm automatically when you type in a random a and b (given that b > a)

Any help would be appreciated.


Solution 1:

This isn't really supposed to be a 'please write code for me' site but the Bresenham algorithm is so simple it was just as quick to write it as to suggest how you should write it.

function sequence = euclideansequence(events, beats)
    increment = events / beats;
    sequence = ''; % initialise the sequence
    last = 0;
    for ii = 1:beats
        current = last + increment;
        if floor(current) > floor(last)
            bit = '1';
        else
            bit = '0';
        end
        sequence = strcat(sequence, bit); % append bit to the sequence
        last = current;
    end
end

This returns the output as a character vector:

>> euclideansequence(5, 12)

ans =

    '001010010101'

If you want it in some other form, it shouldn't be too hard to figure out how to modify the code.