"Mark" <medwar19.nospam@hotmail.com> wrote in message <gq5g3d$kch$1@fred.mathworks.com>...
> Hi,
>
> I want to rotate a binary number by one each iteration but only if the adjacent location is empty.
>
> Examples:
>
> 01110000 becomes
> 00111000
>
> 01011011 becomes
> 00101111
>
> 01110011 becomes
> 00111011
>
> I could use a loop to perform the function but thought there might be a math function to collapse the array in this fashion.
>
> Thanks for looking.
You haven't specified the form your binary numbers are to be in, Mark. They might be in a binary string, a vector of 1's and 0's, a single double number, a single fixedpoint number, or whatever.
I'll assume here that they are in the form of a row vector of 1 and 0 digit values (not a string) with the most significant binary digits first. Call such a vector x and do this:
n = max([find(diff([x 1])>0),1]); %Locate the rightmost 0 digit
x(1:n) = [x(n),x(1:n1)]; % Rotate a portion of x to the right by one
Then x is rotated by one as you require.
If your number is in a different form, you can probably convert the code above fairly easily. The essential idea is to locate the rightmost zero binary digit and rotate right by one all the digits from there on to the left of it. The purpose of the 'max' call is to avoid referencing x(0) when there is nothing to rotate.
Roger Stafford
