Does randperm work with objects rather than integer?.

13 visualizaciones (últimos 30 días)
Maya Nielan
Maya Nielan el 19 de Mayo de 2016
Comentada: Walter Roberson el 19 de Mayo de 2016
I am trying to shuffle a deck of cards and am using
function obj = shuffle(obj)
obj.carddeck = obj.carddeck(randperm(length(obj.carddeck)));
end
yet when i print out the instance of "carddeck", each object or "card" is in the same position and there is no change

Respuestas (1)

Walter Roberson
Walter Roberson el 19 de Mayo de 2016
In that code, randperm is being applied to the integer length(obj.carddeck) not to some other kind of object. What-ever your problem might be is elsewhere.
You could, for debugging purposes, break out the randperm into a temporary variable, so that you could see that it is working properly; that would allow you to check that your indexing is returning a new order and that your revised obj has the new order.
My guess would be that you are calling the shuffle routine without assigning the result to the original object.
  2 comentarios
Maya Nielan
Maya Nielan el 19 de Mayo de 2016
how do I assign the result to the original object? My working portion of the code is below up until 'end'
temp = Card.empty();
for x = 1:52
temp(x) = obj.carddeck(randsample(52,1));
end
obj.carddeck = temp;
I know the temporary variable "temp" is correctly working and holds a randomly sorted vector of "Card"s.
However reassigning my property "carddeck" using
obj.carddeck = temp;
doesn't work.
Walter Roberson
Walter Roberson el 19 de Mayo de 2016
That version of the code uses selection with replacement, so it is not suitable for shuffling. Your original code looks fine. However, when you call the shuffle code, you cannot simply use
shuffle(MyDeck)
or
MyDeck.shuffle
and you instead need to use
MyDeck = shuffle(MyDeck)
or
MyDeck = MyDeck.shuffle
If you want to be able to use simply
MyDeck.shuffle
as the syntax, then you need to switch to handle objects instead of structures or value objects.

Iniciar sesión para comentar.

Categorías

Más información sobre Logical en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by