Borrar filtros
Borrar filtros

Creating an array of objects in a class

4 visualizaciones (últimos 30 días)
Jeffrey Alido
Jeffrey Alido el 29 de Ag. de 2017
Editada: per isakson el 1 de Sept. de 2017
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!

Respuestas (1)

Robert U
Robert U el 29 de Ag. de 2017
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 comentario
Robert U
Robert U el 29 de Ag. de 2017
It is not a "safe" solution. Unsupported inputs are not detected (e.g. Nleaves = 0).

Iniciar sesión para comentar.

Categorías

Más información sobre Methods en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by