'cell'类型输入参数的未定义函数或方法'shuffle'



我正在尝试创建一个具有shuffle和deal方法的类"Deck",但是,我不知道为什么我的"shuffle"函数没有运行。我收到错误消息:

对于类型为"cell"的输入参数,未定义的函数或方法"shuffle"。

有人能解释一下为什么函数没有运行吗?非常感谢。我正在调用以前创建的classdef‘Card’

classdef Deck < handle;
properties;
diamond;
spade
heart;
club;

end;
methods;
function obj=create(deck);
for k=1:13;
%Designate a number to each suit to create the deck
obj(k).diamond=cards('D','R',k);
obj(k).spade=cards('S','B',k);
obj(k).heart=cards('H','R',k);
obj(k).club=cards('C','B',k);
end
%Create a vector of each suit and number accordingly until we
%have 52 cards. 13 of each suit.
obj={obj.diamond obj.spade obj.heart obj.club};            
end
%%
function obj=shuffle(obj);
shuff=randperm(52);
for k=1:52;  
hf=shuff(k);
obj(k)=obj(hf);

end
end
end
end

您不需要构造函数中的最后一行:

obj = { obj.diamond obj.spade obj.heart obj.club }

这条线将您的对象变成一个单元格(?)。请尝试删除此行。尝试此classdef而不是

classdef Deck 
properties 
cards
end
methods
function obj = Deck()
% do your stuff here, but no obj. before diamond/spade/heart/club
obj.cards = { diamond, spade, heart, club };
end 
function obj  =shuffle ( obj )
obj.cards = obj.cards( randperm(52) );
end
end

我认为您想要一个属性,它是Card对象的数组。有关对象数组,请参阅MATLAB文档。以下是我解决这个问题的方法:

classdef Deck < handle
properties
% This will be an object array of Card objects.
CardArray
end
properties (Dependent)
nCards
end
methods 
function This = Deck()
% preallocate arrays.
% the constructor for Card should accept 0 arguments.
Diamond(13) = Card('D', 'R', 13);
Spade(13) = Card('S', 'B', 13);
Heart(13) = Card('H', 'R', 13);
Club(13) = Card('C', 'B', 13);
% now fill in the rest of each suit
for iVal = 1:12
Diamond(iVal) = Card('D', 'R', iVal);
Spade(iVal) = Card('S', 'B', iVal); 
Heart(iVal) = Card('H', 'R', iVal); 
Club(iVal) = Card('C', 'B', iVal);  
end
% finally concatenate them into a single array
This.CardArray = [Diamond, Spade, Heart, Club];
end
function shuffle(This) 
This.CardArray = This.CardArray(randperm(This.nCards)); 
end
function n = get.nCards(This)
n = length(This.CardArray);
end
end
end

您需要确保Card构造函数接受零个参数。例如,您可以执行以下操作:

classdef Card < handle
properties
symbol = 'D'
color = 'R'
value = 1;
end
methods
function This = Card(varargin)
if nargin >= 1
This.symbol = varargin{1};
end
if nargin >= 2
This.color = varargin{2};
end
if nargin >= 3
This.value = varargin{3};
end
end
end
end

最新更新