有什么好的方法可以简化以下逻辑操作? [英] Any good ways to simplify the following logical operation?
问题描述
我正在执行类似于以下逻辑操作的操作:
I am doing the something similar to the following logical operation:
例如,对(x,y), x and y
的测试仅采用0或1的值,因此,有4种不同的选择:(0,0), (0,1), (1,0) and (1,1)
.我希望如果(0,0)
发生,则程序执行function00
; (0,1) for function01
; (1,0) for function10
和(1,1) for function11
.
For example, test for (x,y), x and y
takes values of 0 or 1 only, hence, there are 4 different choices: (0,0), (0,1), (1,0) and (1,1)
. I want that if (0,0)
happens, then the program execute function00
; (0,1) for function01
; (1,0) for function10
and (1,1) for function11
.
当然,我可以使用if then else
编写它,但是我想这样做有点长.
Of course, I can use if then else
to write it, but I guess it is a little bit length to do it.
if x==0 && y==0
'run function00'
else if x==0 && y==1
'run function01'
else if x==1 && y==0
'run function10'
else if x==1 && y==1
'run function11'
end
end
end
end
这里要点是使用它-然后-else使代码不可读.我尝试使用switch
在某种意义上使其更具可读性:
The point here is using it-then-else makes the codes to be unreadable. I try to use switch
to make it more readable in some sense:
switch (x,y)
case (0,0)
'run function00'
case (0,1)
'run function01'
case (1,0)
'run function10'
case (1,1)
'run function11'
end
但是,当我使用switch
时,问题是当将大小写设置为(0,0), (0,1), (1,0) and (1,1)
时存在语法错误.我想知道如何解决它,或者我不知道的其他操作可以做同样的事情.有人可以提出一些建议吗?在这里,假设我已经定义了function00.m
,function01.m
,function10.m
和function11.m
.
However, when I use switch
, the problem is that there is a syntax error when I set the cases to be (0,0), (0,1), (1,0) and (1,1)
. I wonder how to fix it, or other operations that I do not know can do the same thing. Could anybody give some suggestions on it? Here, assuming I have defined function00.m
, function01.m
, function10.m
and function11.m
already.
推荐答案
我建议避免使用eval
并改用函数句柄.定义函数句柄的单元格数组
I would suggest avoiding eval
and using function handles instead. Define a cell array of function handles
>> fh = cell(2,2);
>> fh{1,1} = @function00; fh{1,2} = @function01; % And so on for all four elements
>> out = fh{x+1,y+1}(); % Where x y are your binary variables
这篇关于有什么好的方法可以简化以下逻辑操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!