Using findobj() on Heterogeneous handle object array

조회 수: 5 (최근 30일)
Lennart Scherz
Lennart Scherz 2020년 11월 6일
편집: Walter Roberson 2025년 3월 27일
Hello,
I ran into a problem when working with heterogenous class hierarchies. I created a superclass Body which is derived from handle and matlab.mixin.Heterogeneous :
classdef Body < matlab.mixin.Heterogeneous
...
end
%-----------------------------------
classdef RigidBody < Body
...
end
%-----------------------------------
classdef FlexBody < Body
...
end
The problem that I now ran into came when I combine these two derived classes in a heterogenous array from the class Body. I can't use the function findobj() on that array to find an object with a specific property value,
When trying to find an object with a specific object property whichw as defined in the Body class
% init heterogenous array a
a(1) = RigidBody(...)
a(2) = FlexBody(...)
% find body with name body_1
findobj(a, 'name', 'body_1')
I get the error message
Error using Body/findobj
Unable to call method 'findobj' because one or more inputs of class 'Body' are heterogeneous and 'findobj' is not sealed. For more
details please see the method dispatching rules for heterogeneous arrays.
Is there any kind of work around, since findobj is a method inhereted by the handle class and I therefore can't just seal it.
Thanks!

답변 (1개)

Adarsh
Adarsh 2025년 3월 27일
편집: Walter Roberson 2025년 3월 27일
I have faced a similar issue calling an unsealed function on an array of Heterogeneous objects.
This issue occurs because functions that are applied on heterogeneous object arrays needed to be sealed in the base class to ensure uniformity of the function around all the elements by preventing the subclassing of the sealed functions.
Here is an alternate workaround that worked for me:
  1. Wrap the original “findobj” function inside another function in base class.
  2. Seal the wrapper function.
  3. Inside the wrapper function apply the “findobj”function to each element using a for loop or “arrayfun”individually.
Here is a sample code demonstrating the workaround:
classdef Body < matlab.mixin.Heterogeneous & handle
properties
name
end
methods (Sealed)
function obj = findBodyByName(objArray, varargin)
% Initialize a logical array to store matches
matches = false(size(objArray));
% Loop through each element in the array
for i = 1:numel(objArray)
% Use findobj on each individual element with varargin
foundObj = findobj(objArray(i), varargin{:});
% Check if findobj found anything
if ~isempty(foundObj)
matches(i) = true;
end
end
% Return the objects that match the criteria
obj = objArray(matches);
end
end
end
For more information on heterogeneous object arrays please refer to the following documentation link:
I hope this helps.

카테고리

Help CenterFile Exchange에서 Construct and Work with Object Arrays에 대해 자세히 알아보기

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by