Azzera filtri
Azzera filtri

What is the reason for clearing a struct variable?

3 visualizzazioni (ultimi 30 giorni)
Nalini
Nalini il 15 Nov 2016
Commentato: Walter Roberson il 16 Nov 2016
I went through a code where a struct variable is cleared i.e.
clear S % S is a struct variable
What is the necessity to do such a operation? Thanks a lot the help!
  1 Commento
dpb
dpb il 16 Nov 2016
Necessity? Probably none. Saves some memory if it's no longer needed.
There are referencing syntax possibilities that could possibly cause an error if there's another S later on, but in general even those get automagically reallocated to the new type silently.
Would have to see the usage in context to be able to tell for certain, but I'd venture it (the structure S, that is) has simply served its purpose and the author is just "cleaning up" unused flotsam. Perhaps a table was built from the content which is going to be used from here on, who knows???

Accedi per commentare.

Risposte (1)

Walter Roberson
Walter Roberson il 16 Nov 2016
struct is an unusual case. If you have an existing struct that is possibly empty or possibly non-scalar, but might be scalar, then doing an assignment
S.some_field = some_value
is risky, because you cannot assign to a field in an empty structure or a non-scalar structure. That assignment does not write over the complete S variable the way that
ABC = 12345
would overwrite all of ABC.
Furthermore, for a few years now, if S is a struct then
S = 12345
will not write over all of S: it will instead generate an error about a non-struct assignment to a struct.
Even if you know that S is a scalar struct, assigning to a field of it does not overwrite the entire struct, so if you were wanting to start over with the struct and did not want to just "clear" it, then you would have to rmfield of whatever fields it might happen to contain.
For these various reasons, if you plan to use the same variable again for a different purpose afterwards and it happens to be a struct now, then it is a good idea to clear the struct, due to considerations that are not there for numeric variables or characters or logical or strings.
  2 Commenti
Philip Borghesani
Philip Borghesani il 16 Nov 2016
Walter your statement that a simple assignment does not replace a structure supprised me and I can't reproduce it in current versions. What matlab versions does it reproduce in?
clear s;
s.field=5;
s=10
s =
10
Walter Roberson
Walter Roberson il 16 Nov 2016
Ah, I had it reversed, the error is in assigning a struct to a non-struct object.

Accedi per commentare.

Categorie

Scopri di più su Structures in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by