I wrote the following code:

7 次查看(过去 30 天)
Diptangshu Sen
Diptangshu Sen 2018-9-8
I wrote the following code:
classdef agent
properties
office_neighbours
family
state
endproperties
methods
function obj = agent(m,n)
obj.family = m;
obj.state = n;
endfunction
function n = updateagent(obj,a,b)
[obj.office_neighbours(1)] = a;
[obj.office_neighbours(2)] = b;
n = obj.office_neighbours;
endfunction
endmethods
endclassdef
Then, from the command line, I send the following commands:
>> x = agent(2,3)
x =
[object agent]
>> disp(x.family)
ans=2
>> disp(x.state)
ans = [] (0X0)
Similarly, when I call
>> updateagent(x,2,3)
I get the answer
ans =
2 3
But, when I call
>> x.office_neighbours
I get the following
ans =
[] (0X0)
I dont know what is going on. Please help me out.

回答(1 个)

Walter Roberson
Walter Roberson 2018-9-9
You are not using a handle object. When you update the object inside the class methods, you are updating a temporary copy of the object, not the original object. You would need to output the object and assign the result over top of the original object to update it.
The rules are different for handle objects, which effectively gives you a pointer to the real object, and assigning into that updates the only copy of the object.
  7 个评论
Diptangshu Sen
Diptangshu Sen 2018-9-15
I changed the constructor method to one without any arguments. Even, the first one called with agent(m,n) threw the same error. I bet the problem is something else. Also, I could not get what you were talking about end statements.
Walter Roberson
Walter Roberson 2018-9-15
You are not using MATLAB. You are using Octave, which is a different programming language. We do not have the knowledge or resources to assist with differences between MATLAB and octave. You should consult an octave resource, or else you should rewrite in MATLAB and test in MATLAB.
If you choose to test in MATLAB then we will need to see your revised class definition and calling code.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Software Development Tools 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by