Cannot accèss methods of an Object after modified

5 ビュー (過去 30 日間)
Umit
Umit 2012 年 2 月 15 日
I have following codes as junk.m & junk2.m
classdef junk
properties
myValue = [];
end
methods
function obj = junk() % constructor
obj.myValue = 11;
end
function obj = me()
end
end
end
function junk2()
obj = junk(); % construct an object of myClass
obj.myValue = 2; % set some fancy values to the object
obj2 = myFunction(obj); % pass the object to a nice function
disp(obj2.myValue) % verify that myValue has changed
end
function obj = myFunction(obj3)
obj.myValue = obj3.myValue + 1;
end
When I call this function I get following output for methods
methods(obj2)
Methods for class struct:
amd ctranspose fieldnames ichol linsolve permute struct2cell
cholinc display fields ilu luinc reshape transpose
methods(obj)
Methods for class junk:
junk me
How can I get both junk $ me methods after I call myFunction(Obj) method?

採用された回答

Honglei Chen
Honglei Chen 2012 年 2 月 15 日
You need to use handle object. Use the following line in your class definition
classdef junk < handle
You can then write your function as
function myFunction(obj)
obj.myValue = obj.myValue+1;
end

その他の回答 (2 件)

Honglei Chen
Honglei Chen 2012 年 2 月 15 日
You need to instantiate the class first in myFunction. The code as is just create a struct obj in myFunction that has a field named myValue.
function obj = myFunction(obj3)
obj = junk;
obj.myValue = obj3.myValue + 1;
end
BTW, you may want to pay more attention to class names and variable names, make them meaningful.
  2 件のコメント
Umit
Umit 2012 年 2 月 15 日
The problem is, this is the basic version of my program, I have a complex series of methods $ functions and I need to update object's properties from another method w/o losing same object's methods. How can I do that with updating objects parameters from different functions (something different than constructor of the object).
Honglei Chen
Honglei Chen 2012 年 2 月 15 日
I started a new answer so I can format the code

サインインしてコメントする。


Umit
Umit 2012 年 2 月 16 日
Great it works fine. Thank you.

カテゴリ

Help Center および File ExchangeProperties についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by