What is the reason for clearing a struct variable?

3 次查看(过去 30 天)
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 个评论
dpb
dpb 2016-11-16
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???

请先登录,再进行评论。

回答(1 个)

Walter Roberson
Walter Roberson 2016-11-16
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 个评论
Philip Borghesani
Philip Borghesani 2016-11-16
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 2016-11-16
Ah, I had it reversed, the error is in assigning a struct to a non-struct object.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by