Arrays from object properties within object arrays

5 Ansichten (letzte 30 Tage)
Michael
Michael am 19 Mai 2020
Kommentiert: Michael am 19 Mai 2020
I want to know if there is an efficent way to extract an array of values from properties of objects in an object array. Let's say I have an class called 'car' with one property 'mpg' that is set with its constructor method.
prius = car(55); % create prius car and set mpg to 55
tacoma = car(22); % create tacoma car and set mpg to 22
Let's also say that I create an array of cars called inventory
inventory = [prius; tacoma];
Is there a way to extract the properties of all the cars as a vector without a 'for' loop? I know I could do the following
for i = 1:length(inventory)
mpg_list(i) = inventory(i).mpg;
end
but I would like a single line command like
mpg_list = inventory(:).mpg
If I execute the last line in the command window I get
mpg_list =
55
which is the first value, but I want all of them so that mpg_list = [55; 22].

Akzeptierte Antwort

Ameer Hamza
Ameer Hamza am 19 Mai 2020
val = [inventory.mpg];

Weitere Antworten (0)

Kategorien

Mehr zu Matrices and 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!

Translated by