OOP: Select Data with conditional
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Nycholas Maia
am 27 Nov. 2018
Bearbeitet: Matt J
am 29 Nov. 2018
I would like to filter a array of objects (animal class) and get a new array of objects that fits in 2 properties conditions simultaneally.
Example:
I want to get all animals that have more than 5 years old and less than 10 inches of height.
My animal class is:
classdef animal
properties
age % years
height % inches
name % string
end
end
So I can create animals objects like
dog1 = animal();
dog1.age = 10;
dog1.height = 15;
dog1.name = "Bob";
cat1 = animal();
cat1.age = 2;
cat1.height = 10;
cat1.name = "Alice";
And than put all animals objects in same array, like:
my_array = {dog1, cat1, ...};
How can I "filter" my_array using 2 conditionals (age and height)?
0 Kommentare
Akzeptierte Antwort
Luna
am 27 Nov. 2018
Hi Nycholas,
Try this code below. Filtered array will return to you Jessie and Kayle which meets the conditions.
dog1 = animal();
dog1.age = 10;
dog1.height = 15;
dog1.name = 'Bob';
cat1 = animal();
cat1.age = 2;
cat1.height = 10;
cat1.name = 'Alice';
dog2 = animal();
dog2.age = 10;
dog2.height = 8;
dog2.name = 'Jessie';
cat2 = animal();
cat2.age = 6;
cat2.height = 3;
cat2.name = 'Kayle';
my_array = {dog1, cat1,dog2,cat2};
idx = logical(zeros(1,numel(my_array)));
for i = 1:numel(my_array)
if my_array{i}.age > 5 && my_array{i}.height < 10
idx(i) = true;
end
end
filteredArray = my_array(idx);
4 Kommentare
Luna
am 29 Nov. 2018
Bearbeitet: Luna
am 29 Nov. 2018
It does nothing to do with OOP, I think what you need is a kind of table structure for that magical way below.
filtered_array = some_function(my_array, midi_note = 50, duration > 10, instrument = "Piano")
You should set a good defined tables for what you need or be using a database.
(You can still continue to use OOP)
Weitere Antworten (1)
Matt J
am 29 Nov. 2018
Bearbeitet: Matt J
am 29 Nov. 2018
In this scenario, it is better to have a single object whose properties are arrays than an array of objects whose properties are scalars. However, the following should be faster than looping,
my_array = [my_array{:}]; %get rid of cell array storage
conditions = [my_array.age]>5 & [my_array.height]<10;
filtered_array = my_array(conditions);
0 Kommentare
Siehe auch
Kategorien
Mehr zu Construct and Work with Object Arrays finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!