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

12 vues (au cours des 30 derniers jours)
William Kozicki
William Kozicki le 3 Août 2017
Modifié(e) : per isakson le 4 Août 2017
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.

Réponse acceptée

Image Analyst
Image Analyst le 3 Août 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
  1 commentaire
William Kozicki
William Kozicki le 3 Août 2017
Yep, that is pretty much what I was looking for. Thanks!

Connectez-vous pour commenter.

Plus de réponses (1)

per isakson
per isakson le 4 Août 2017
Modifié(e) : per isakson le 4 Août 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

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by