Looping through bytes of a variable
조회 수: 5 (최근 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)
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!