Looping through bytes of a variable
Ältere Kommentare anzeigen
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 Kommentar
Guillaume
am 6 Dez. 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
Akzeptierte Antwort
Weitere Antworten (1)
Walter Roberson
am 6 Dez. 2016
y8 = reshape( typecast(y, 'uint8'), 8, []);
Now you can cross-over on the rows.
Afterwards you can typecast(y8, 'double')
2 Kommentare
Caleb
am 6 Dez. 2016
Walter Roberson
am 6 Dez. 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)
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!