Arrays from object properties within object arrays

4 次查看(过去 30 天)
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].

采纳的回答

Ameer Hamza
Ameer Hamza 2020-5-19
val = [inventory.mpg];

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 MATLAB Compiler 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by