Looping through bytes of a variable
5 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commento
Guillaume
il 6 Dic 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
Risposta accettata
Guillaume
il 7 Dic 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))
0 Commenti
Più risposte (1)
Walter Roberson
il 6 Dic 2016
y8 = reshape( typecast(y, 'uint8'), 8, []);
Now you can cross-over on the rows.
Afterwards you can typecast(y8, 'double')
2 Commenti
Walter Roberson
il 6 Dic 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)
Vedere anche
Categorie
Scopri di più su Logical in Help Center e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!