2016-11-27 64 views
2

我用我自己的類my_class像創造了MATLAB對象本如何找到由自己的類創建的對象?

car = my_class(); 

classdef my_class < handle 

    properties 
     color = 'red'; 
    end 

    methods 
     function obj = my_class() 
      % ... 
     end 
    end 
end 

現在我想通過它的類(my_class)或屬性,找到我的對象(color )。但是findallfindobj總是返回一個空矩陣,無論我在做什麼。你有任何線索嗎?謝謝。

編輯我需要的是這樣的:

car1 = my_classA(); 
car2 = my_classA(); 
house1 = my_classB(); ... house25 = my_classB(); 
tree1 = my_classC(); ... tree250 = my_classC(); 

在我的代碼,我不能指手柄的名稱(如car2.color),因爲我有很多不同的對象,我要搜索他們通過一個函數,看起來像下列操作之一:

loop over all objects (maybe with findobj/findall without knowing object name/handle) 
    if object is of class `my_classA` 
     get handle of `my_classA` 
     change `color` 
    else if object is of class `my_classB` 
     get handle of `my_classB` 
     do something ... 
    end 
end 
+0

你爲什麼要這麼做?你的用例是什麼? –

+0

我需要更改屬性或需要調用多個對象的方法。但是我需要首先在某種類型的循環或類似環境中搜索指定的對象,因爲我想通過它們的值而不是它們的句柄來獲取對象。 – Lemonbonbon

+0

...但爲什麼你不收集數組中的那些對象呢? –

回答

2

我覺得你只是想這樣的:

% Create example array of objects 
A(20) = object; 
[A([3 14 17]).color] = deal('blue'); 

% Get those objects which are red, and change to orange 
[A(strcmp({A.color}, 'red')).color] = deal('orange'); 

我不得不承認,findobj會好得多讀。 但是,據我所知,這隻適用於圖形手柄,所以你必須爲你的課程重載它。

而且那個重載的函數會包含類似於這個的東西。

編輯由納文指出,這個工程:

B = findobj(A, 'color', 'red'); 
[B.color] = deal('orange'); 

似乎比strcmp方法快了。

+2

findobj應該在這種情況下工作正常。 B = findobj(A,'color','red'); [bcolor] = deal('orange');只要您將句柄作爲第一個輸入傳遞,findobj就可以用於句柄類。 – Navan

+0

@Navan是的,它確實:我站得更正了。 –

+0

謝謝,但那不完全是,我正在尋找。我需要一些(第一)遍歷所有自己的對象(不使用或不知道對象的句柄),然後(第二個)獲取特定對象的句柄。 – Lemonbonbon