How do I make a list of objects that have specific properties?

12 visualizaciones (últimos 30 días)
Hello. I'm trying to make this program for a homebrewed D&D thing for fun but am having some difficulties. I feel like I am woefully under informed about classes and how to use them.
I've defined a class for Ingredients
classdef Ingredient
properties
Rarity;
Location;
Easy;
Medium;
Hard;
VeryHard;
Weight;
Passive;
end
methods
end
end
What I want to be able to do is (after creating all of my ingredients) search for all ingredients of a specific location(s).
I understand this is a relatively simple question. Is there something I have to do when I create my objects? I am going about this in a way that makes any sense?
Thanks.

Respuesta aceptada

Image Analyst
Image Analyst el 3 de Ag. de 2017
What about strcmp() in a simple for loop. Assuming you have your array of ingredient objects:
for k = 1 : length(allIngredients)
if strcmp(allIngredients(k).Location, 'pantry')
message = sprintf('The location of ingredient #%d is your pantry', k);
uiwait(helpdlg(message));
end
end

Más respuestas (1)

per isakson
per isakson el 4 de Ag. de 2017
Editada: per isakson el 4 de Ag. de 2017
An alternate approach
%%Create some data
loc = randi( [double('A'),double('D')], 1,8 );
loc_str = arrayfun( @char, loc, 'uni',false );
loc_num = num2cell(loc);
%
%%Create an array of objects
allIngredients(1,8) = Ingredient; % preallocate an array of objects
[allIngredients.Location] = loc_str{:}; % assign some values
[allIngredients.Rarity] = loc_num{:};
%
%%Search for all ingredients with location equal to 'A'.
isA = strcmp( {allIngredients.Location}, 'A' );
allIngredients(isA).Rarity

Categorías

Más información sobre Loops and Conditional Statements 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