Automatically update attributes of a class ?

2 visualizaciones (últimos 30 días)
Neelay Doshi
Neelay Doshi el 28 de Jul. de 2020
Comentada: Matt J el 28 de Jul. de 2020
Hi everyone.
I have a class called "Rect" (rectangle) which has 4 attributes: lenght (l), breadth (b), area (A) and perimeter (P). I wish to initialize the class using only the length and breadth and I want it to calculate the area and perimeter automatically. Later when I change its length or breadth I want the class to update the value of its area and perimeter automatically. I have been able to do this in python using the "@property" syntax as I have shown below:
class Rect:
def __init__(self, _l, _b):
self.l= _l #lenght
self.b= _b #breadth
pass
@property
def A(self): #area of rectangle
return self.l*self.b
@property
def P(self): #perimeter of rectangle
return 2*(self.l+self.b)
Following is an example of object in python:
rect_1= Rect(2, 3)
print(rect_1.A)
6
rect_1.l= 3
print(rect_1.A)
9
I wish to do exactly this in MATLAB, is there any equivalent?

Respuesta aceptada

Matt J
Matt J el 28 de Jul. de 2020
Editada: Matt J el 28 de Jul. de 2020
This has to go in a file called Rect.m :
classdef Rect
properties
l,b
end
properties (Dependent,Hidden)
A,P
end
methods
function obj=Rect(l,b)
obj.l=l; obj.b=b;
end
function A=get.A(obj)
A=obj.l*obj.b;
end
function P=get.P(obj)
P=obj.l+obj.b;
end
end
end
and now you would do
>> rect_1= Rect(2, 3); rect_1.A
>> rect_1.l= 3; rect_1.A
  2 comentarios
Neelay Doshi
Neelay Doshi el 28 de Jul. de 2020
This is exactly what I wanted! Thank you!
Matt J
Matt J el 28 de Jul. de 2020
You're welcome, but please Accept-click the answer to indicate so.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Call Python from MATLAB en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by