Looping through bytes of a variable
6 次查看(过去 30 天)
显示 更早的评论
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 个评论
Guillaume
2016-12-6
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
采纳的回答
Guillaume
2016-12-7
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))
0 个评论
更多回答(1 个)
Walter Roberson
2016-12-6
y8 = reshape( typecast(y, 'uint8'), 8, []);
Now you can cross-over on the rows.
Afterwards you can typecast(y8, 'double')
2 个评论
Walter Roberson
2016-12-6
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)
另请参阅
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!