필터 지우기
필터 지우기

What is the reason for clearing a struct variable?

조회 수: 3 (최근 30일)
Nalini
Nalini 2016년 11월 15일
댓글: Walter Roberson 2016년 11월 16일
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