Help with class methods please
Show older comments
I'm pretty new to Matlab. I'm writing code that creates simulated images of rod-like particles diffusing in a liquid. I'm trying to use OOP to do this so I can keep track of positions and angles of the particles. My constructor method for the rods works fine, but I have a method to make them move and rotate that doesn't work. When I just write out the code in a function to test it it works so I'm guessing it's just something in the syntax that makes it not work when I call the method.
classdef rod
properties
rodlength;
i_pos=0;
j_pos=0;
angle;
frame;
methods
function step(d,z,stepsize)%z is the simulated image the rod is put into
I want step to change the position and angle of some rod object d (I didn't include all the code inside the method because its long and boring). When I call the method, by saying rod_1.step(frame, 50) nothing happens, i.e. the image before and after I invoke the method is the same. However if I write out all the code outside the object it works so I think it has something to do with the way I call it. Any suggestions? Thanks.
Accepted Answer
More Answers (1)
Eric
on 21 Jun 2012
I think per isakson's answer is a bit simplistic. You should probably read up on the difference between Handle classes and Value classes and then decide which type of class you need. Handle classes are not always the right solution. See
If you're only ever going to create one instance of a rod object, then a Handle class is probably fine. Without the "< handle" suffix in the classdef line, you have a Value class. In that case you should use
obj = obj.step(d, z, stepsize);
Good luck,
Eric
2 Comments
per isakson
on 21 Jun 2012
I would rather call it a "hint".
Eric
on 22 Jun 2012
My apologies, simplistic is indeed overly harsh. I just wanted to make sure the OP is aware of what he's doing and that it may induce some other unexpected behaviors. I've had colleagues suffer from this same issue with Matlab classes. They've gone to great lengths in writing overly complicated code because they think Matlab only allows shallow copies of objects. I believe they may have been using the Handle class type without fully understanding what that means.
Categories
Find more on Scripts 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!