Method set don't work

4 次查看(过去 30 天)
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
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 个)

产品

Community Treasure Hunt

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

Start Hunting!

Translated by