Arrays from object properties within object arrays

4 visualizzazioni (ultimi 30 giorni)
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].

Risposta accettata

Ameer Hamza
Ameer Hamza il 19 Mag 2020
val = [inventory.mpg];

Più risposte (0)

Categorie

Scopri di più su Matrices and Arrays in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by