是否有可以像VBA的IIF一样放在INLINE中的Matlab条件IF运算符 [英] Is there a Matlab conditional IF operator that can be placed INLINE like VBA's IIF

查看:151
本文介绍了是否有可以像VBA的IIF一样放在INLINE中的Matlab条件IF运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在VBA中,我可以执行以下操作:

In VBA I can do the following:

A = B + IIF(C>0, C, 0)

因此,如果C> 0,我得到A=B+C,而C< = 0,我得到A=B

so that if C>0 I get A=B+C and C<=0 I get A=B

在MATLAB代码中是否存在可以让我内联执行这些条件的运算符或函数?

Is there an operator or function that will let me do these conditionals inline in MATLAB code?

推荐答案

在Matlab中没有三元运算符.当然,您可以编写一个可以执行此操作的函数.例如,以下函数用作iif,条件为n-d输入,结果为ab时,使用数字和单元格:

There is no ternary operator in Matlab. You can, of course, write a function that would do it. For example, the following function works as iif with n-d input for the condition, and with numbers and cells for the outcomes a and b:

function out = iif(cond,a,b)
%IIF implements a ternary operator

% pre-assign out
out = repmat(b,size(cond));

out(cond) = a;


对于更高级的解决方案,有一种方法可以创建甚至可以执行其他操作的内联函数,如您将此功能用作

iif(condition_1,value_1,...,true,value_final)

用任意数量的附加条件/值对替换点.

where you replace the dots with any number of additional condition/value pairs.

此方法的工作方式是从值中选择第一个条件为真的值. 2*find(),1,'first')提供值参数的索引.

The way this works is that it picks among the values the first one whose condition is true. 2*find(),1,'first') provides the index into the value arguments.

这篇关于是否有可以像VBA的IIF一样放在INLINE中的Matlab条件IF运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆