How do I make a list of objects that have specific properties?
8 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
William Kozicki
il 3 Ago 2017
Modificato: per isakson
il 4 Ago 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.
0 Commenti
Risposta accettata
Image Analyst
il 3 Ago 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
Più risposte (1)
per isakson
il 4 Ago 2017
Modificato: per isakson
il 4 Ago 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
0 Commenti
Vedere anche
Categorie
Scopri di più su Direct Search 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!