필터 지우기
필터 지우기

How do I find all entries in an object array with a certain property

조회 수: 20 (최근 30일)
Carla White
Carla White 2018년 2월 13일
편집: per isakson 2020년 1월 17일
Hi all, this is my first time attempting an object orientated program in Matlab so please bear with me. I have created an object array that for each object in the array has the properties 'Position' and 'Value'. Position saves the position within the array and Value will be either 0 or 1. I would like to be able to find the position of all entries with a 1 as the value. In a normal array I would have used the 'find' command. I have tried using 'findobj' but this results in an error saying I cannot use the method findobj on a class handle. Is there another way I can do this? My code atm is
classdef ObjectArray
properties
Value
Position
Timer
NbH1
NbH2
end
methods
function Cell = ObjectArray(M)
if nargin ~= 0
m = size(M,1);
n = size(M,2);
Cell(m,n) = ObjectArray;
for i = 1:m
for j = 1:n
Cell(i,j).Value = M(i,j);
Cell(i,j).Position=[i,j];
end
end
end
end
end
end
Thanks for the help, Carla

답변 (2개)

Benjamin Kraus
Benjamin Kraus 2018년 2월 13일
There are a variety of ways you can do this. The most straightforward is to use arrayfun:
arr = ObjectArray(rand(10)>0.5);
ind = arrayfun(@(o) o.Value == 1, arr);
pos = vertcat(arr(ind).Position);
  댓글 수: 1
Benjamin Kraus
Benjamin Kraus 2018년 2월 13일
Another option is to overload find for your class, and internally call arrayfun (or any other internal implementation you want):
classdef ObjectArray
...
methods
function ind = find(objarr)
ind = arrayfun(@(o) o.Value == 1, objarr);
end
end
end

댓글을 달려면 로그인하십시오.


per isakson
per isakson 2020년 1월 17일
편집: per isakson 2020년 1월 17일
Another approach
>> cc = ClassC( 12 );
>> [cc.a]
ans =
17 17 17 17 17 17 17 17 17 17 17 17
>> [cc([4,7,11]).a] = deal(1);
>> [cc.a]
ans =
17 17 17 1 17 17 1 17 17 17 1 17
This was a matlabish way to create a sample object array. Now find() finds the ones this way
>> find([cc.a]==1)
ans =
4 7 11
>>
where
classdef ClassC < handle
properties
a double = 17;
end
methods
function this = ClassC( n )
if nargin >= 1
this( 1, n ) = ClassC();
end
end
end
end

카테고리

Help CenterFile Exchange에서 Graphics Object Programming에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by