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

查看:22
本文介绍了是否有可以像 VBA 的 IIF 一样内联放置的 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 工作,条件为 nd 输入,结果为 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;

<小时>

对于更高级的解决方案,有一种方法可以创建一个甚至可以执行 elseif 的内联函数,如 这篇关于匿名函数恶作剧的博文:

iif  = @(varargin) varargin{2*find([varargin{1:2:end}], 1, 'first')}();

您将此功能用作

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 一样内联放置的 Matlab 条件 IF 运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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