필터 지우기
필터 지우기

Automatically update attributes of a class ?

조회 수: 7 (최근 30일)
Neelay Doshi
Neelay Doshi 2020년 7월 28일
댓글: Matt J 2020년 7월 28일
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?

채택된 답변

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

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Call Python from MATLAB에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by