2016-05-17 99 views
-1
classdef hello < handle 
     methods 
      function first(obj) 
       a=4; 
       function second(obj) 
        a 
       end 
      end 
     end 
end 

我希望能夠調用函數「obj.second」。調用類中的嵌套函數

這是我曾嘗試:

>> hello_obj=hello; 
>> hello_obj.first 
>> hello_obj.second 
No appropriate method, property, or field second for class hello. 

>> hello_obj.first.second 
Attempt to reference field of non-structure array. 

>> hello_obj.first.hello_obj.second 
Attempt to reference field of non-structure array. 

謝謝

+0

這是不可能的,你爲什麼認爲你必須這樣做? – Daniel

+0

我想利用嵌套函數可以訪問父函數的工作空間的事實(我不希望「a」是屬性)。 –

+0

當你嘗試調用'second'時,'a'不再存在。我認爲一個財產將是最好的解決方案,但你可以解釋你的理由不使用財產。這可能會導致更好的解決方案。 – Daniel

回答

1

使用Transient屬性a保存時跳過它。對於無法應用Transistent的情況,重載saveobj and loadobj是一個很好的選擇。

+0

你能幫我使用它嗎?抱歉。 classdef hello properties a = 4 end properties(Transient = true)b = 23 end end >> hello_obj = hello; >> save('hello_obj')hello_obj.mat包含一個包含兩個屬性的對象。 –

+0

@Michaël:不,它不會將'b'存儲在mat文件中,它會使用將其設置爲23的構造函數重新初始化。嘗試'hello_obj = hello; hello_obj.a = 5; hello_obj.b = 24; save('hello_obj'); clear hello_obj; 加載('hello_obj')' – Daniel

+0

謝謝!實際上,我不希望hello_obj.b被保存,甚至作爲一個空變量。 –