1

In the MATLAB OOP framework, it can be useful to cast an object to a struct, i.e., define a function that takes an object and returns a struct with equivalent fields.

What is the appropriate place to do this? I can think of several options:

  • Build a separate converter object that takes care of conversions between various classes
  • Add a function struct to the class that does the conversion to struct, and make the constructor accept structs

Neither option seems to be very elegant: the first means that logic about the class itself is moved to another class. On the other hand, in the second case, it provokes users to use the struct function for any object, which will in general give a warning (structOnObject).

Are there altenatives?

2 Answers 2

1

Personally I'd go with the second option, and not worry about provoking users to call struct on other classes; you can only worry about your own code, not that of a third-party, even if the third party is MathWorks. In any case, if they do start to call struct on an arbitrary class, it's only a warning; nothing actually dangerous is likely to happen, it's just not a good practice.

But if you're concerned about that, you can always call your converter method toStruct rather than struct. Or perhaps the best (although slightly more complex) way might be to overload cast for your class, accepting and handling the option 'struct', and passing any other option through to builtin('cast',....

PS The title of your question refers to typecasting, but what your after here is casting. In MATLAB, typecasting is a different operation, involving taking the exact bits of one type and reinterpreting them as bits of another type (possibly an array of the output type). See doc cast and doc typecast for more information on the distinction.

Sign up to request clarification or add additional context in comments.

Comments

0

The second option sounds much better to me.

A quick and dirty way to get rid of the warning would be disabling it by calling

warning('off', 'MATLAB:structOnObject')

at the start of your program.

The solutions provided in Sam Roberts' answer are however much cleaner. I personally would go for the toStruct() method.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.