I would like to create a card-deck class in MatLAB. This is my first time experiencing OOP with MatLAB, and I’m fairly new to MatLAB. I’m thinking of having 2 classes:
- card (properties: type [1-4], value [1-13])
- deck (containing a list/vector of the cards in the deck, I will later define methods for this class; shuffle, drawCard, etc.)
card.m:
classdef card
properties
type; % number: 1-4
value; % number: 1-13
end
methods
function obj = card(type, value)
% some code to check [type, value] should be inserted here
obj.type = type;
obj.value = value;
end
end
end
This being a raw structure of my class, functionality will come later. Now – how do I define the deck class?
I would also like to be able to let my deck class communicate with my card instances (to make sure I call the right cards: [card(1,1), card(1,2), card(1,3), …, card(4, 13)], for example.
Any suggestions?
Thanks in advance!
You need to implement a subsref function to handle indexing a deck object if you want to address directly into a deck, ie:
or add a function with indexing parameters:
The last one seems more appropriate, and also easier to implement:
or just use:
which is just the same, without the explicit error checking.
Also add an parameter-less constructor to
card, so you can easily createcardarrays: