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

13 ビュー (過去 30 日間)
William Kozicki
William Kozicki 2017 年 8 月 3 日
編集済み: per isakson 2017 年 8 月 4 日
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.

採用された回答

Image Analyst
Image Analyst 2017 年 8 月 3 日
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 件のコメント
William Kozicki
William Kozicki 2017 年 8 月 3 日
Yep, that is pretty much what I was looking for. Thanks!

サインインしてコメントする。

その他の回答 (1 件)

per isakson
per isakson 2017 年 8 月 4 日
編集済み: per isakson 2017 年 8 月 4 日
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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by