Method set don't work

조회 수: 8 (최근 30일)
Thierry NOVO
Thierry NOVO 2013년 7월 15일
I wrote a simple program to understand how to implement a set method. Here is my code. First the class definition:
classdef Material
properties
L
nz
dz
end
methods
function newMat = Material(L, nz)
if nargin == 2
newMat.L = L;
newMat.nz = nz;
newMat.dz;
end
end
function dz = get.dz(newMat)
dz = newMat.L/( newMat.nz - 1);
end
function newMat = set.dz(newMat,value)
newMat.dz = value;
end
end
end
Then a simple script:
clc; close all; clear all; clear classes;
cm = 1e-02; Mat1 = Material(5*cm,11);
so Mat1.dz is equal to 0.005 But when i want to set Mat1.dz = 0.1, the result remains equal to 0.005. Why the set method doesn't work ?? Thanks in advance for your help

채택된 답변

Lokesh Ravindranathan
Lokesh Ravindranathan 2013년 7월 15일
Your code is working correctly. The reason why the set method appears like not working is because the get method is dependent on L and nz. Since the values of L and nz are unchanged, the get method always calculates the value of dz and it remains at 0.005, although the set method is used with different values. Consider modifying your code.
Initialize dz when you create the object and always get the current value of dz for display (no calculations).
classdef Material
properties
L
nz
dz
end
methods
function newMat = Material(L, nz)
if nargin == 2
newMat.L = L;
newMat.nz = nz;
newMat.dz = L/(nz-1);
end
end
function dz = get.dz(newMat)
dz = newMat.dz;
end
function newMat = set.dz(newMat,value)
newMat.dz = value;
end
end
end
  댓글 수: 1
Thierry NOVO
Thierry NOVO 2013년 7월 15일
편집: Thierry NOVO 2013년 7월 15일
Thank you so much Lokesh for your answer. I tried your proposition and it works.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by