【发布时间】:2021-02-04 23:26:54
【问题描述】:
问题是有效的三元运算,因为我无法在网上找到任何与之相关的文档。而且我还发现在 MATLAB 中不可能使用三进制,因此任何建议和答案都将在此不胜感激。
#三元运算代码
taxes = (income > 50000)*(((income-50000) * 0.20)+(0.10*50000)) + (~(income > 50000))*0.10 *50000
#Condition True and this computation False then this computation
#带有 if 和 else 的代码
if (income) > 50000
#income = income - 50000
#Taxed at 10% (i.e 0.10) for $ 50000
#taxes = 50000 * 0.10
#Rest income will be Taxed at 20% (i.e 0.20)
taxes = 50000 * 0.10 + ((income-50000) * 0.20)
else
#Taxed at 10% (i.e 0.10)
taxes = income * 0.10
endif
输出:
GNU Octave, version 6.1.0
Copyright (C) 2020 The Octave Project Developers.
This is free software; see the source code for copying conditions.
There is ABSOLUTELY NO WARRANTY; not even for MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. For details, type 'warranty'.
Octave was configured for "x86_64-w64-mingw32".
Additional information about Octave is available at https://www.octave.org.
Please contribute if you find this software useful.
For more information, visit https://www.octave.org/get-involved.html
Read https://www.octave.org/bugs.html to learn how to submit bug reports.
For information about changes from previous versions, type 'news'.
>> income = 60000;
>> compute_taxes
taxes = 7000
>> income = 50000;
>> compute_taxes
taxes = 5000
>>
【问题讨论】:
-
您的“三元运算代码”在 Octave 和 MATLAB 中有效。它不是真正的三元运算符,但会产生等效的结果。
if/else代码的优势在于它可以处理数组,而不仅仅是标量值。 -
另外,请将终端输出复制粘贴到问题中,而不是上传屏幕截图。原因见here。
-
我知道它不是,但我试图复制它,我是 Octave 的初学者,但我已经知道 python,所以我尝试了这段代码。@CrisLuengo 是的,它为我提供了相同的功能
-
那么问题到底是什么?你似乎已经有了一些你想要的代码?
-
也许将其写入问题文本以使其更清晰。在 Octave 中有
mergeorifelse(它们似乎是一样的),这可能是(类似于)你想要的
标签: matlab octave conditional-operator