How to determine if an object is a built-in class?
14 views (last 30 days)
Show older comments
How can I determine if an object is a built-in class?
Not only doubles, structs, strings and all those base data types but also stuff like figures, dynamic systems (tf & ss objects)
2 Comments
Steven Lord
on 26 Apr 2024
Why? How would you handle those types of data differently than instances of classes defined by non-MathWorks code?
Answers (1)
Steven Lord
on 26 Apr 2024
Okay. You could achieve your stated goal without actually having to ask "Is this an instance of my class or an instance of some other class or other data type?" If you had a method named struct for your class, or if you defined a non-Static method with some other name that accepted just one input, then the input would be an instance of your class. In the case of struct the method would be a converter method, while if it were some other name that returned a struct it would be just an ordinary instance method.
Or if you do need to ask if the object is an instance of one of the classes you created, you don't need to ask the broad question "Is this an instance of a type MathWorks provided?" You could ask a more targeted question, asking if the variable isa instance of one of your classes.
2 Comments
Steven Lord
on 26 Apr 2024
I was trying to find a universal way to avoid specifying classes that I want to convert so that it can be applied to any custom tool anybody will write in the future.
So you want to write a function that can accept any array and turn it into a struct? That's a very tall order.
Instead what I would focus on would be overloading struct for your classes. That way you can convert only the pieces of the object that users need to know about (leaving out any internal implementation details.) You could probably delegate some of that work to the built-in struct function and prune out any internal properties that shouldn't be included in the struct.
c = onCleanup(@() disp('bye')) % object in MATLAB without a struct overload
which -all struct(c)
s1 = struct(c) % Call the built-in function; note the warning
s2 = builtin('struct', c) % Would call the built-in even if there's an overload
See Also
Categories
Find more on Data Type Conversion in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!