Creating an array of objects in a class

2 次查看(过去 30 天)
I have two .m files for class tree and class leaf:
classdef Tree
properties
leaves = [];
for i = 1:100
leaves = [leaves Leaf]
end
end
%
methods (Static = true)
function show
for i = 1:100
leaves(i).show
end
end
end
end
and
classdef Leaf
properties
pos = [rand*200 rand*200]
end
methods (Static = true)
function show
disp('this is a leaf')
end
end
end
I'd like to be able create a Tree object with an array of Leaf objects. How may I do this? I'd also like to make the "show" function work.
Thanks!

回答(1 个)

Robert U
Robert U 2017-8-29
Hi Jeffrey,
here my solution for your tree with leafs:
Tree.m:
classdef Tree
properties
leaves = [];
end
methods
function obj = Tree(nLeaves)
obj = obj.CreateLeaves(nLeaves);
end
function obj = CreateLeaves(obj,N)
for ik = 1:N
if ~isempty(obj.leaves)
obj.leaves(end+1) = Leaf();
else
obj.leaves = Leaf();
end
end
end
function showTree(obj)
if ~isempty(obj.leaves)
fprintf('The tree has %d leaves.\n\n',length(obj.leaves));
for ik = 1:length(obj.leaves)
fprintf('Leaf %d:\n',ik);
obj.leaves(ik).show;
end
else
fprintf('The tree has no leaves.\n');
end
end
end
end
Leaf.m:
classdef Leaf
properties
pos = [];
end
methods
function obj = Leaf(~)
obj = obj.RandomPos;
end
function show(obj)
fprintf('This is a single leaf at (%.2f, %.2f).\n\n',obj.pos(1),obj.pos(2))
end
end
methods (Access = private)
function obj = RandomPos(obj)
currSetting = rng;
rng('shuffle');
obj.pos = [rand*200 rand*200];
rng(currSetting);
end
end
end
Create a tree with 5 leaves:
myTree = Tree(5)
Show full tree:
myTree.showTree
Show a single leaf:
myTree.leaves(4).show
  1 个评论
Robert U
Robert U 2017-8-29
It is not a "safe" solution. Unsupported inputs are not detected (e.g. Nleaves = 0).

请先登录,再进行评论。

类别

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

Community Treasure Hunt

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

Start Hunting!

Translated by