avoid loop in this funcion
Afficher commentaires plus anciens
hi guys, I want to avoid loop in this function which a for shuffling cards, are there any suggestions?
function s = shuffle(x)
n = length(x)/2;
s = []
for i = 1:n
if rand(1) > 0.5
s = [s x([2*i-1 2*i])]
else
s = [s x([2*i 2*i-1])];
end
end
Réponses (2)
Your code randomly swaps adjacent pairs of elements of x. This can be done without a loop:
function x = shufflepairs(x)
V = 2:2:numel(x);
Y = rand(1,numel(V))>0.5;
x = x(reshape([V-Y;V-~Y],1,[]));
end
And tested:
>> shufflepairs(0:9)
ans =
0 1 3 2 5 4 6 7 8 9
This works for x with an even number of elements. I leave it up to the reader to handle an odd number of elements.
Jan
le 13 Jan 2018
The loop is no problem, only the missing pre-allocation is. A cleaner version:
function s = shuffle(x)
s = reshape(x, 2, []);
for k = 1:size(s, 2)
if rand(1) > 0.5
s(:, k) = s([2,1], k);
end
end
s = s(:).';
end
Now a vectorization is done by inserting the index of the FOR loop into the operation. Here you need to consider the random part also:
function s = shuffle(x)
s = reshape(x, 2, []);
q = rand(1, size(s, 2)) > 0.5;
s(:, q) = s([2,1], q); % Swap pairs if rand is > 0.5
s = s(:).';
end
Catégories
En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!