Looping through bytes of a variable

1 view (last 30 days)
Caleb
Caleb on 6 Dec 2016
Answered: Guillaume on 7 Dec 2016
I'm doing a genetic algorithm with real parameter values. Say that I have two candidate solutions:
x(1) = 1.2345678
x(2) = 8.7654321
And I want to perform a crossover. I pick a random location along the length of the variables using randi and get, say, 3. Then I want to switch the values before the 3rd byte such that my output would be:
y(1) = 1.2654321
y(2) = 8.734567
How would you program this?
  1 Comment
Guillaume
Guillaume on 6 Dec 2016
Is there a confusion here and are you looking at swapping digits in a decimal representation rather than bytes? Swapping bytes will result in numbers that bear absolutely no resemblance to the original numbers. For example, if you swap the 8th bytes of your two numbers, you'll end with:
>>format longg
>>x = [1.2345678; 8.7654321]
x =
1.2345678
8.7654321
>>y = reshape(typecast(x, 'uint8'), 8, []); %swapping 8th byte
>>y(8, [2 1]) = y(8, [1 2]);
>>newx = typecast(y(:), 'double')
newx =
80908.6353408
0.000133749879455566

Sign in to comment.

Accepted Answer

Guillaume
Guillaume on 7 Dec 2016
From your example, I'm not sure that you actual want to swap the bytes of the number, but actually want to swap the decimal digits of the numbers. Swapping bytes, = 8 bits of the number represented in binary, makes absolutely no sense to me.
Assuming you want to swap digits after the decimal:
x = [1.2345678; 8.7653421];
decimaltoswap = 2;
y = x - mod(x, 10^(1-decimaltoswap)) + mod(x([2 1]), 10^(1-decimaltoswap))

More Answers (1)

Walter Roberson
Walter Roberson on 6 Dec 2016
y8 = reshape( typecast(y, 'uint8'), 8, []);
Now you can cross-over on the rows.
Afterwards you can typecast(y8, 'double')
  2 Comments
Caleb
Caleb on 6 Dec 2016
Is there any way that I can loop through the values byte-by-byte. Something more like:
nBytes = 8;
CutLocation = randi([1,nBytes]);
for i = 1:nBytes
if i < CutLocation
y1(i) = x1(i);
y2(i) = x2(i);
else
y1(i) = x2(i);
y2(i) = x1(i);
end
end
Obviously, i would have to be looping through bytes instead of an index of a vector, but hopefully you get the idea.
Walter Roberson
Walter Roberson on 6 Dec 2016
x12 = reshape( typecast(x, 'uint8'), 8, []);
x1 = x12(:,1);
x2 = x12(:,2);
Followed by your loop.
Or skip the loop and do
x12 = reshape( typecast(x, 'uint8'), 8, []);
x12(CutLocation:end, [1 2]) = x12(CutLocation:end, [2 1]);
y12 = typecast(x12, 'double');
The reconstructed values will be y12(1) and y12(2)

Sign in to comment.

Products

Community Treasure Hunt

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

Start Hunting!