Setting object properties from a class method
Mostrar comentarios más antiguos
Hi,
I'm exploring OOP with matlab and have the following code:
% method declaration
function Update(obj, Time)
obj.DeltaTime = Time; % saves time parameter to a class-wide property
obj.Height = obj.Height + obj.DeltaHeight; % new tank height
end
DeltaTime, Height are public properties of the class this sits inside. I call the method using the following syntax:
% method call
Update(TankA, 7)
There are other methods that use DeltaTime to calculate DeltaHeight. These all work perfectly fine. However, calling this method doesn't change the DeltaTime property, nor set Height to its new value. I don't get any errors thrown when the code runs, so have no idea why its not working as I expect it to. I don't know how to pass the values to the properties as method outputs either:
% using method outputs
function [DeltaTime, Height] = Update(obj,Time)
DeltaTime = Time;
Height = obj.Height + DeltaHeight;
end
Ideally I want DeltaTime, DeltaHeight to be private properties, and not manipulated directly from a separate file. Can someone please give me an idea what could be causing this?
Respuesta aceptada
Más respuestas (1)
Image Analyst
el 11 de Ag. de 2012
What is obj? Is it some other object? It's not the same object is it? If it is, why aren't you simply doing:
function Height = Update(Time)
Height = Height + Time;
end
You don't even need DeltaTime since it's the same as Time that you passed in.
2 comentarios
Manish Makwana
el 11 de Ag. de 2012
Robert Jack
el 17 de Abr. de 2018
I don't understand why this is the accepted answer. In my view the answer by per isakson is better. I'm troubled why an mvp is asking what 'obj' is when the context is clearly that of class properties.
Categorías
Más información sobre Methods en Centro de ayuda y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!