Effacer les filtres
Effacer les filtres

Rand in the constructor of a class and createArray

30 vues (au cours des 30 derniers jours)
Andrew Doppenberg
Andrew Doppenberg le 15 Juil 2024 à 21:31
Réponse apportée : Walter Roberson le 15 Juil 2024 à 23:11
I'm attempting to use createArray to create an array of a class. The class constructor sets a property using rand. When I use createArray, every object in the array gets the same value of that property. Is there a workaround?

Réponses (2)

Andres Adam
Andres Adam le 15 Juil 2024 à 22:11
Modifié(e) : Walter Roberson le 15 Juil 2024 à 23:09
It seems that createArray is not creating a new object for each element, but rather creating one and copying on the rest of the elements.
Maybe a workaround is to specify a copy method for your class, so the property changes with rand even when it is copied. Have you tried that?

Walter Roberson
Walter Roberson le 15 Juil 2024 à 23:11
When you have static properties of the class, then the value that is assigned when the class is loaded is used for all subsequent members of the class. To change the value, you need to clear the class.
In short... you should not have assigned a per-instance property at the class level.

Catégories

En savoir plus sur Construct and Work with Object Arrays dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by