still not getting the oop concept... please help

1 次查看(过去 30 天)
i got the following code:
classdef node
properties
x;
y;
bearing=0;
end % properties
methods
function obj = node(x,y)
obj.x=x;
obj.y=y;
end%functions
end%methods
end %class
classdef manlists
properties
nodelist ;
end
methods
function h = AddNode(self,a,b) % Add a node with 2 coordinates
if (isempty(self.nodelist))
self.nodelist = [node(a,b)];
else
self.nodelist(self.grN+1,1) = node(a,b); %grN gives the size of nodeslist
end
end
end
end
lets say i have my instance called man = manlists; if i call it by man.AddNode(1,2) it returns the node buts doesnt store it in man; in other words : i can call man man.AddNode(1,1) as many times i want but the nodelist cantaines just one element;
if i call it by men = man.AddNode(1,2) it does what i want it to do,
the thing is that i have to call this like 10000 times wihin the programm and i gues that this makes it really slow
in C i would use a pointer for this....
does anyone has a sugestion??
thanks a lot

回答(1 个)

Kye Taylor
Kye Taylor 2012-4-27
You can get the behavior you want if you subclass the handle class.
To do this, 1.) replace the line
classdef manlists
with
classdef manlists < handle
and 2.) remove the output from the AddNode() method.
  3 个评论
Daniel Shub
Daniel Shub 2012-4-28
@Jeff One of the reasons your code is slow is that you are creating and destroying things every time (another is that MATLAB OOP is just slow).
High level languages like MATLAB do not need pointers, in essence everything in MATLAB is a pointer and it only copies (allocates new memory for) things when it needs to. Handle classes help MATLAB know that you want to change the current copy, such that everything that points to it also changes, and not to make a new copy.
It is not clear to me why you think it makes your code more complicated.
Kye Taylor
Kye Taylor 2012-4-29
@Jeff, it's unclear what is more efficient. I would suggest experimenting with both implementations. It would be interesting to hear what you find works better.
Check out a recent post at <http://blogs.mathworks.com/loren/2012/03/26/considering-performance-in-object-oriented-matlab-code/> for some related information. Bottom line is that this suggests that if you're using loops and calling that method often, it is likely more efficient if you can keep that loop inside the method itself.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Software Development Tools 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by