Filter löschen
Filter löschen

Automatically update attributes of a class ?

7 Ansichten (letzte 30 Tage)
Neelay Doshi
Neelay Doshi am 28 Jul. 2020
Kommentiert: Matt J am 28 Jul. 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?

Akzeptierte Antwort

Matt J
Matt J am 28 Jul. 2020
Bearbeitet: Matt J am 28 Jul. 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 Kommentare
Neelay Doshi
Neelay Doshi am 28 Jul. 2020
This is exactly what I wanted! Thank you!
Matt J
Matt J am 28 Jul. 2020
You're welcome, but please Accept-click the answer to indicate so.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Call Python from MATLAB finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by