Effacer les filtres
Effacer les filtres

Automatically update attributes of a class ?

7 vues (au cours des 30 derniers jours)
Neelay Doshi
Neelay Doshi le 28 Juil 2020
Commenté : Matt J le 28 Juil 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?

Réponse acceptée

Matt J
Matt J le 28 Juil 2020
Modifié(e) : Matt J le 28 Juil 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 commentaires
Neelay Doshi
Neelay Doshi le 28 Juil 2020
This is exactly what I wanted! Thank you!
Matt J
Matt J le 28 Juil 2020
You're welcome, but please Accept-click the answer to indicate so.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Call Python from MATLAB dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by