How do I create an array of abstract class objects in MATLAB?
-
As an example, suppose I have created an abstract class called Shape and two subclasses called Circle and Rectangle that both implement an (abstract) method called Draw. I would like to be able to create a number of Circle and Rectangle objects, store them in an array and call Draw on each array object by iterating through the array. I have tried something like the following: Shape.m: classdef (Abstract) Shape < handle methods (Abstract) Draw(obj); end end Circle.m: classdef Circle < Shape methods function obj = Draw(obj) disp('This is a circle'); end end end Rectangle.m: classdef Rectangle < Shape methods function obj = Draw(obj) disp('This is a rectangle'); end end end test.m: shapes = Shape.empty(); myrect = Rectangle(); mycirc = Circle(); shapes(end + 1) = myrect; shapes(end + 1) = mycirc; for i = 1:size(shapes,1) shapes(i).Draw(); end When I try to run test.m, I get the following error message: Error using Shape.empty Abstract classes cannot be instantiated. Class 'Shape' defines abstract methods and/or properties. Error in test (line 1) shapes = Shape.empty();
-
Answer:
You can use a cell array. A cell array's contents can be any type of data structure my_c_array{1}=rect_object my_c_array{3}=shape_object my_c_array{4}=47.23 my_c_array{5}='monkey' then later you can grab your structs from the array and do whatever you want with them tmp_var=my_c_array{1}
Sulimon Sattari at Quora Visit the source
Related Q & A:
- how can i remove an array from an array?Best solution by Stack Overflow
- How can I overload equal method to make different objects have same hashcode value in unordered_multimap?Best solution by Stack Overflow
- How do I create a digital signature and how do I use it?Best solution by support.office.com
- How can I construct the array problem?Best solution by Stack Overflow
- How Can I Create an XML to Create a Menu?Best solution by Drupal Answers
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
For every problem there is a solution! Proved by Solucija.
-
Got an issue and looking for advice?
-
Ask Solucija to search every corner of the Web for help.
-
Get workable solutions and helpful tips in a moment.
Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.