我怎么说(A&B)或MATLAB中的C?

49次观看(最近30天)
Adriano
Adriano on 26 Feb 2016
编辑: Kevin Claytor on 26 Feb 2016
Hi! I have three conditions A, B and C. I would like to set: if both A and B or C in Matlab. I thought to:
如果(A && B)|C
but It doesn't work. How can i do it? Thanks!
2 Comments
亚当
亚当 on 26 Feb 2016
从您的使用来判断|而不是||我怀疑您也可能想要,而不是&&

Sign in to comment.

接受的答案

Kevin Claytor
Kevin Claytor on 26 Feb 2016
编辑:Kevin Claytor on 26 Feb 2016
|operates elementwise on arrays. You might want to check the size of A, B, and C. 如果 then operates on the array (See @Stephen's answer).
>>help |
|Logical or.
A |B执行a logical or of arrays A and B and returns an array
containingelements set to either logical 1 (TRUE) or logical 0
(FALSE)....
NoteMATLAB中有两个逻辑或操作员。The |
operator执行元素或矩阵之间的元素,尽管
||操作员执行a short-circuit or between scalar values.
我更喜欢使用&&和||出于多种个人原因:
  • Certainly when I was starting out, I didn't consider the possibility of the behavior of如果operating on a vector. Keeping statements to the scalar operators adds implicit error-checking when you hand your code to someone else - they'll now get an error (&& doesn't operate on vectors) instead of a possibly ill-defined result. Of course, if you intend to operate on vectors, you can ignore this comment.
  • As @Stephen mentioned below, it doesn't have to evaluate the rest of the expression once the condition is met. Just make sure all of your () are in the right places.
  • It forces you to think a bit more about about the intent of the condition, for example do you want:所有(a)to be true, or would you be happy if任何(a)是真的吗?即使“如果全部(a)”的默认值等于“如果A”,您刚刚明确了意图。
  • 来自其他语言的人可能以不同的方式解释意图。例如在Python中;
>>如果[0,0,0]:
print(“是的”)
>>是的
(因为[0,0,0]不是没有。)而;
>>如果all([0, 0, 0]):
print(“是的”)
>>
2 Comments
Kevin Claytor
Kevin Claytor on 26 Feb 2016
You're right. I shot that off without thinking too much about it. Upon reflection, I think I was in two places at once; matrix size and personal preference. I've updated my answer to hopefully make the distinction more clear.

Sign in to comment.

更多的回答s (1)

Stephen23
Stephen23 on 26 Feb 2016
编辑:Stephen23 on 26 Feb 2016
您需要考虑 size 您的操作数。您没有告诉我们它们的尺寸,但这对于我们知道您应该做什么是非常重要的信息。
This is explained quite clearly in the 如果 文档: "An expression is true when its result is nonempty and contains only nonzero elements (logical or real numeric). Otherwise, the expression is false."
意思是:
  • 如果[0,0,0,0]is false: all values are zero
  • 如果[0,1,0,1]is false: some values are zero
  • 如果〜[0,0,0,0] = [1,1,1,1]is true:仅包含非零元素
  • 如果〜[0,1,0,1] = [1,0,1,0]is false: some values are zero
Note that the definition defines a true expression as “仅包含非零元素” but does not give an upper-limit to the number of nonzero elements. It is likely that you have multiple elements, some of which are false. then your 如果 不会运行。

社区寻宝

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

开始狩猎!