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개)

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 CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by