[英]Function to avoid 'Index exceeds matrix dimensions'
I have problem with MATLAB - or at least I cannot solve it at the moment and if I look after that specific error message than I get very complicated examples. 我在MATLAB上遇到问题-或至少目前无法解决它,并且如果我照看该特定错误消息,则会得到非常复杂的示例。 Brought to its total base, my problem looks as follows: 综合考虑,我的问题如下:
I have to program a Connect-Four game. 我必须编写一个四人连线游戏。 The game field is initalized with zeros that way: 这样,游戏字段会以零开头:
Field = zeros([6 7]);
Later on, I have to check for the win condition. 稍后,我必须检查获胜条件。 However, if I do something like 但是,如果我做类似的事情
if GameField(7, 7) == xxx
then it obviously fails, as the game field has just six columns. 那么显然失败了,因为游戏领域只有六列。 The exact error message is 'Index exceeds matrix dimensions' - and I can definitely understand why this is. 确切的错误消息是“索引超出矩阵尺寸”-我绝对可以理解为什么会这样。
Is there any function, which can help me to avoid that error (in a way like try-catch in programming languages). 是否有任何功能可以帮助我避免该错误(以编程语言中的try-catch之类的方式)。 I know for example that there is a function called exists
, but this does only work with variables, etc. - but not with matrix dimensions. 例如,我知道有一个函数称为exists
,但这仅适用于变量等,但不适用于矩阵尺寸。 Using the length()
-function would be quite tricky when dealing with diagonal values. 在处理对角线值时,使用length()
-函数将非常棘手。 I'm actually looking for a function (where I do not know the name) that works the following 我实际上正在寻找一个可以正常工作的函数(其中我不知道名字)
if valueExists(GameField(7, 7))
%do something
else
%do something other
end
You know the size of the field, store that in a variable called fieldSize
. 您知道字段的大小,然后将其存储在名为fieldSize
的变量中。
fieldSize = [6 7];
Thus, you can conveniently initialize the field as 因此,您可以方便地将字段初始化为
Field = zeros(fieldSize);
Next, when you want to perform checks, for example whether the value to the bottom right of the current position is 1, you can always check against fieldSize
first 接下来,当您要执行检查时,例如当前位置右下角的值是否为1,您始终可以先检查fieldSize
currentPosition = [1 7];
bottomRight = currentPosition - [1 1];
if any(bottomRight < 1 | bottomRight > fieldSize)
% do not check b/c out of field
else
% perform check
end
Alternatively, you could optimize your search strategy so that you never look outside the field in the first place. 另外,您可以优化搜索策略,以免您一开始就不在视野之外。 For example a diagonal of four going bottom left to top right can never start in columns 5:7. 例如,从左下到右上的四个对角线永远不会在5:7列开始。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.