Arrays from object properties within object arrays

4 visualizaciones (últimos 30 días)
Michael
Michael el 19 de Mayo de 2020
Comentada: Michael el 19 de Mayo de 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].

Respuesta aceptada

Ameer Hamza
Ameer Hamza el 19 de Mayo de 2020
val = [inventory.mpg];

Más respuestas (0)

Categorías

Más información sobre Matrices and Arrays en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by