Got Questions? Get Answers.
Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
conditional operator

Subject: conditional operator

From: Dietrich Lueerssen

Date: 30 Apr, 2007 07:43:56

Message: 1 of 28

Hi there fellow MATLABers,

I have recently had the following "problem": I wanted to define a
function such as the sinc function (sin(x)/x), which for x->0
approaches 1, but obviously MATLAB throws a division by zero error.
The solution is simple enough (define the function in an m-file, use
an if-statement, and test for the "offending" input). Done that,
works fine.

Here is my question for the community: ideally I would have liked to
define an anonymous function (sinc = @(x) sin(x)/x;), but that does
not allow the if-statement. In C, I would have used the conditional
operator "?", as in ( (x==0)?1:sin(x)/x ).
I am not aware of MATLAB having such a nice tool; does somebody know
a simple way to achieve the same thing?

Dietrich

Subject: conditional operator

From: david bateman

Date: 30 Apr, 2007 14:35:22

Message: 2 of 28

Dietrich Lueerssen wrote:
> Hi there fellow MATLABers,
>
> I have recently had the following "problem": I wanted to define a
> function such as the sinc function (sin(x)/x), which for x->0
> approaches 1, but obviously MATLAB throws a division by zero error.
> The solution is simple enough (define the function in an m-file, use
> an if-statement, and test for the "offending" input). Done that,
> works fine.
>
> Here is my question for the community: ideally I would have liked to
> define an anonymous function (sinc = @(x) sin(x)/x;), but that does
> not allow the if-statement. In C, I would have used the conditional
> operator "?", as in ( (x==0)?1:sin(x)/x ).

Want is the syntax of the "?" operator if "x" is other than a scalar?

> I am not aware of MATLAB having such a nice tool; does somebody know
> a simple way to achieve the same thing?
>
> Dietrich

Define a function like

function y = sinc (x)
  [dummy, idx] = find (x == 0);
  x = sin (x) ./ x;
  x(idx) = 0 ;
end

and then create a function handle (not an anonymous function handle) as
"@sinc".. Note you'll need to suppress the warning about division by
zero though.

D.

Subject: conditional operator

From: Dietrich Lueerssen

Date: 30 Apr, 2007 08:56:08

Message: 3 of 28

David Bateman wrote:
>
>
> Dietrich Lueerssen wrote:
>> Hi there fellow MATLABers,
>>
>> I have recently had the following "problem": I wanted to define
a
>> function such as the sinc function (sin(x)/x), which for
x->0
>> approaches 1, but obviously MATLAB throws a division by zero
> error.
>> The solution is simple enough (define the function in an
m-file,
> use
>> an if-statement, and test for the "offending" input). Done
that,
>> works fine.
>>
>> Here is my question for the community: ideally I would have
liked
> to
>> define an anonymous function (sinc = @(x) sin(x)/x;), but that
> does
>> not allow the if-statement. In C, I would have used the
> conditional
>> operator "?", as in ( (x==0)?1:sin(x)/x ).
>
> Want is the syntax of the "?" operator if "x" is other than a
> scalar?
I was only looking to create a
use-once-in-this-context-and-then-forget-it function, which is why I
did not worry about type checking studd like that.

>
>> I am not aware of MATLAB having such a nice tool; does somebody
> know
>> a simple way to achieve the same thing?
>>
>> Dietrich
>
> Define a function like
>
> function y = sinc (x)
> [dummy, idx] = find (x == 0);
> x = sin (x) ./ x;
> x(idx) = 0 ;
> end
>
> and then create a function handle (not an anonymous function
> handle) as
> "@sinc".. Note you'll need to suppress the warning about division
> by
> zero though.
>
> D.
>
 
Dear David,
Thank you for your suggestion; my solution was the following function
file:
------------
function y = sinc(x)
% SINC(x):
% calculates the value of sin(x)/x; in case x is equal to zero, the
% return value is 1 (since lim(x->0) sin(x)/x = 1).
state = warning('query', 'MATLAB:divideByZero');
warning('off', 'MATLAB:divideByZero');

y = sin(x)./x;
y(isnan(y)) = 1;

warning(state.state, 'MATLAB:divideByZero');
-------------

After writing the function file, things are simple enough as you
suggest.

The reason why I wanted to use an anonymous function is that I was
writing a script (rather than a function), and if you want to define
a function you do not need to create an additional file with a
function definition, rather than in a function file where you can
define sub-functions.

As I said before, the problem with the sinc-function definition is
not hard, but I was rather looking for an operator similar to the C
conditional operator.

Best regards,
Dietrich

Subject: conditional operator

From: Steven Lord

Date: 30 Apr, 2007 09:53:49

Message: 4 of 28


"David Bateman" <dbateman@free.fr> wrote in message
news:4635e28a$0$12844$426a34cc@news.free.fr...
> Dietrich Lueerssen wrote:
>> Hi there fellow MATLABers,
>>
>> I have recently had the following "problem": I wanted to define a
>> function such as the sinc function (sin(x)/x), which for x->0
>> approaches 1, but obviously MATLAB throws a division by zero error.
>> The solution is simple enough (define the function in an m-file, use
>> an if-statement, and test for the "offending" input). Done that,
>> works fine.
>>
>> Here is my question for the community: ideally I would have liked to
>> define an anonymous function (sinc = @(x) sin(x)/x;), but that does
>> not allow the if-statement. In C, I would have used the conditional
>> operator "?", as in ( (x==0)?1:sin(x)/x ).
>
> Want is the syntax of the "?" operator if "x" is other than a scalar?
>
>> I am not aware of MATLAB having such a nice tool; does somebody know
>> a simple way to achieve the same thing?

MATLAB does not have the ternary ?: operator, but we do have a request in
the enhancement database for this.

> Define a function like
>
> function y = sinc (x)
> [dummy, idx] = find (x == 0);
> x = sin (x) ./ x;
> x(idx) = 0 ;
> end
>
> and then create a function handle (not an anonymous function handle) as
> "@sinc".. Note you'll need to suppress the warning about division by
> zero though.

With a minor reworking of your function, you can avoid the divide by zero.

function y = sinc (x)
y = ones(size(x));
NZ = x ~= 0;
y(NZ) = sin(x(NZ))./x(NZ);

Alternately, you could write a function:

function y = questioncolon(condition, x1, x2)
% QUESTIONCOLON M-file for C's ?: ternary operator
% Syntax: y = questioncolon(condition, x1, x2)
%
% The elements of the output matrix will be set as:
% y(condition==true) = x1(condition==true)
% y(condition==false) = x2(condition==false)
%
% x1 and x2 can be function handles or matrices the same size as condition
%
% Example:
% x = -10:10;
% y = questioncolon(x==0, @(z) 1, @(z) sin(x(z))./x(z));

y = zeros(size(condition));
y(condition) = x1(condition);
y(~condition) = x2(~condition);

and use it in your anonymous function.

--
Steve Lord
slord@mathworks.com

Subject: conditional operator

From: Yair Altman

Date: 30 Apr, 2007 10:01:59

Message: 5 of 28

the missing ?: ternary function is a well-known Matlab issue for a
long time, and its possible use in anonymous functions (used
extensively in cellfun/arrayfun, for example) is a very sore point...

My solution was to define an iff() function as follows:

    function result = iff(test,trueVal,falseVal)
        try
            if test
                result = trueVal;
            else
                result = falseVal;
            end
        catch
            result = false;
        end
    end

The you can then use it with anonymous functions as follows:

    cellfun(@(x) iff(x==0,0,sin(x)/x), syncData);

Yair Altman

Subject: conditional operator

From: Lars Boyde

Date: 27 Apr, 2009 19:57:01

Message: 6 of 28

I am not aware of an official if-statement that can be implemented in an anonymous function. However, you can (slightly artificially) create your own if-statement by writing yourself a delta-function by using given Matlab functions (such as heaviside, dirac, floor, ceil, etc.)
For your particular problem, two lines suffice:

delta = @(x) heaviside(ceil(abs(x))-0.5);
sinc = @(x) delta(x).*sin(x)./(1-delta(x).*1+x) + (1-delta(x));

The function heaviside(x) assumes value 0 for x<0 and value 1 for x>0. The function ceil(abs(x)) [ceiling] takes value 0 only iff x = 0, otherwise it is >=1. Therefore, subtracting any number smaller than 1 (here 0.5) will yield:
delta(x=0) = 0;
delta(x=~0) = 1;

In your sinc-function you only need to multiply the sin(x)/x with delta(x), such that the statement is essentially unchanged as long as x does not equal 0. For x==0 this term will then vanish (make sure that you also avoid that the denominator is still zero since you will otherwise get the annoying "division by zero"-error). You then have to add the second term in the equation which in most cases (x =~0) vanishes, but when required (x==0) equals 1.
Obviously, you don't necessarily need to define two functions delta(x) and sinc(x), but can include it all in one function. This trick helps you avoiding writing endless m-files and works in many cases where an if-statement is required in an anonymous function handle.
Regards,
Lars

Subject: conditional operator

From: Matt Fig

Date: 27 Apr, 2009 20:14:01

Message: 7 of 28

The only way around such things as this (as far as using anonymous functions) that I know of is by using multiple function evaluations.

f = @(x) [sin(x(x<0))./x(x<0) x(x==0)+1 sin(x(x>0))./x(x>0)] % YUCK!
x = -10:.01:10;
plot(x,f(x))

Subject: conditional operator

From: Matt

Date: 27 Apr, 2009 20:16:01

Message: 8 of 28

"Dietrich Lueerssen" <Dietrich.Lueerssen@REMOVE-THIS.ogt.co.uk> wrote in message <ef55682.-1@webcrossing.raydaftYaTP>...
> Hi there fellow MATLABers,

> In C, I would have used the conditional
> operator "?", as in ( (x==0)?1:sin(x)/x ).

Seems like a bad idea, since you would have numerical problems in the neighbourhood of x=0.

It would be better to use a Taylor approximation of sin(x) for x in a near neighbourhood of the origin. This will lead to an approximation of sin(x)./x which is just a polynomial (i.e. no division by x). Once you've accepted the inevitable complexity of this, you will end up writing this as an mfile anyway....

Subject: conditional operator

From: Jos

Date: 28 Apr, 2009 07:48:03

Message: 9 of 28

"Dietrich Lueerssen" <Dietrich.Lueerssen@REMOVE-THIS.ogt.co.uk> wrote in message <ef55682.-1@webcrossing.raydaftYaTP>...
> Hi there fellow MATLABers,
>
> I have recently had the following "problem": I wanted to define a
> function such as the sinc function (sin(x)/x), which for x->0
> approaches 1, but obviously MATLAB throws a division by zero error.
> The solution is simple enough (define the function in an m-file, use
> an if-statement, and test for the "offending" input). Done that,
> works fine.
>
> Here is my question for the community: ideally I would have liked to
> define an anonymous function (sinc = @(x) sin(x)/x;), but that does
> not allow the if-statement. In C, I would have used the conditional
> operator "?", as in ( (x==0)?1:sin(x)/x ).
> I am not aware of MATLAB having such a nice tool; does somebody know
> a simple way to achieve the same thing?
>
> Dietrich

Assuming you still want sin(x)/x to return NaN for x = 0,
simply turn the warning off will do the trick as well ...

help warning

Jos

Subject: conditional operator

From: Moritz Boecker

Date: 31 Aug, 2010 15:46:04

Message: 10 of 28

I had the same Problem before, solved it a little bit differently. I made the if statement into a seperate function that would return a logical 1 or 0. Then I multiplied the result of my if-function with the result of my function and added the two results. I.e.
let's say
y = 2x | x>2
y = -2x | x <= 2

cond = @(x) (x>2)
func = @(x) cond(x) * 2x + (1-cond(x)) * -2x

"Dietrich Lueerssen" <Dietrich.Lueerssen@REMOVE-THIS.ogt.co.uk> wrote in message <ef55682.-1@webcrossing.raydaftYaTP>...
> Hi there fellow MATLABers,
>
> I have recently had the following "problem": I wanted to define a
> function such as the sinc function (sin(x)/x), which for x->0
> approaches 1, but obviously MATLAB throws a division by zero error.
> The solution is simple enough (define the function in an m-file, use
> an if-statement, and test for the "offending" input). Done that,
> works fine.
>
> Here is my question for the community: ideally I would have liked to
> define an anonymous function (sinc = @(x) sin(x)/x;), but that does
> not allow the if-statement. In C, I would have used the conditional
> operator "?", as in ( (x==0)?1:sin(x)/x ).
> I am not aware of MATLAB having such a nice tool; does somebody know
> a simple way to achieve the same thing?
>
> Dietrich

Subject: conditional operator

From: Matt J

Date: 31 Aug, 2010 17:37:04

Message: 11 of 28

"Matt " <xys@whatever.com> wrote in message <gt53q1$qu6$1@fred.mathworks.com>...
> "Dietrich Lueerssen" <Dietrich.Lueerssen@REMOVE-THIS.ogt.co.uk> wrote in message <ef55682.-1@webcrossing.raydaftYaTP>...
> > Hi there fellow MATLABers,
>
> > In C, I would have used the conditional
> > operator "?", as in ( (x==0)?1:sin(x)/x ).
>
> Seems like a bad idea, since you would have numerical problems in the neighbourhood of x=0.
>
> It would be better to use a Taylor approximation of sin(x) for x in a near neighbourhood of the origin. This will lead to an approximation of sin(x)./x which is just a polynomial (i.e. no division by x). Once you've accepted the inevitable complexity of this, you will end up writing this as an mfile anyway....
=================

I don't think so. Internally, sin() is always implemented using Taylor approximations anyway. It would be redundant to wrap sin() in a 2nd Taylor approximation. In any case, I've never had any numerical problems, even with very small x

>> x=1e-100

x =

  1.0000e-100

>> sin(x)/x

ans =

     1

 

Subject: conditional operator

From: Matt J

Date: 31 Aug, 2010 17:52:19

Message: 12 of 28



One more way,

sinc = @(x) sin( x+ pi*(x==0))./(x+(x==0)) + (x==0)

Subject: conditional operator

From: Jeff

Date: 2 Nov, 2011 03:28:12

Message: 13 of 28

"Dietrich Lueerssen" <Dietrich.Lueerssen@REMOVE-THIS.ogt.co.uk> wrote in message <ef55682.-1@webcrossing.raydaftYaTP>...
> Hi there fellow MATLABers,
>
> I have recently had the following "problem": I wanted to define a
> function such as the sinc function (sin(x)/x), which for x->0
> approaches 1, but obviously MATLAB throws a division by zero error.
> The solution is simple enough (define the function in an m-file, use
> an if-statement, and test for the "offending" input). Done that,
> works fine.
>
> Here is my question for the community: ideally I would have liked to
> define an anonymous function (sinc = @(x) sin(x)/x;), but that does
> not allow the if-statement. In C, I would have used the conditional
> operator "?", as in ( (x==0)?1:sin(x)/x ).
> I am not aware of MATLAB having such a nice tool; does somebody know
> a simple way to achieve the same thing?
>
> Dietrich

As long as x doesn't contain NaNs you can use sinc=@(x) min( sin(x)/x , 1 ).

Since the function being implemented is sinc, sin(x)/x will be smaller than 1 when x~=0, and when x==0, min will ignore the NaN and return the correct value of 1.

Subject: conditional operator

From: Roger Stafford

Date: 2 Nov, 2011 07:20:26

Message: 14 of 28

"Matt J" wrote in message <i5jek0$ntg$1@fred.mathworks.com>...
> "Matt " <xys@whatever.com> wrote in message <gt53q1$qu6$1@fred.mathworks.com>...
> > It would be better to use a Taylor approximation of sin(x) for x in a near neighbourhood of the origin. .......
> I don't think so. Internally, sin() is always implemented using Taylor approximations anyway. It would be redundant to wrap sin() in a 2nd Taylor approximation. In any case, I've never had any numerical problems, even with very small x
> ......
- - - - - - - - -
  Matt J, in general I would tend to agree with the other Matt. In the special case of sin(x)/x, undoubtedly the designers of Mathworks' sine function took special pains to use a polynomial approximation in the vicinity of zero that allows for an accurate sin(x)/x. To do so there need only be an approximation near zero in the form x*(1+x^2*P(x)) for some appropriate polynomial P(x) and I believe this is what has been done.

  However, as a simple example suppose someone wanted to define f(x) as the slope of a chord line on the sine function between x+1 and 1 radians which would be:

 f(x) = (sin(x+1)-sin(1))/x

Using the above operations as they stand loses considerable accuracy near zero. For example for x = 2^(-26) it will lose about half of the available 52 bits of accuracy, whereas a good polynomial approximation to this function in the vicinity of zero can preserve almost all of them.

  {Note: Of course one could use

 f(x) = (sin(x)*cos(1)-2*sin(x/2)^2*sin(1))/x

which would also preserve full accuracy near, though not exactly at, zero but only because of the above argument in the first paragraph.)

Roger Stafford

Subject: conditional operator

From: TideMan

Date: 2 Nov, 2011 07:37:44

Message: 15 of 28

On Nov 2, 8:20 pm, "Roger Stafford"
<ellieandrogerxy...@mindspring.com.invalid> wrote:
> "Matt J" wrote in message <i5jek0$nt...@fred.mathworks.com>...
> > "Matt " <x...@whatever.com> wrote in message <gt53q1$qu...@fred.mathworks.com>...
> > > It would be better to use a Taylor approximation of sin(x) for x in a near neighbourhood of the origin. .......
> > I don't think so. Internally, sin() is always implemented using Taylor approximations anyway. It would be redundant to wrap sin() in a 2nd Taylor approximation. In any case, I've never had any numerical problems, even with very small x
> > ......
>
> - - - - - - - - -
>   Matt J, in general I would tend to agree with the other Matt.  In the special case of sin(x)/x, undoubtedly the designers of Mathworks' sine function took special pains to use a polynomial approximation in the vicinity of zero that allows for an accurate sin(x)/x.  To do so there need only be an approximation near zero in the form x*(1+x^2*P(x)) for some appropriate polynomial P(x) and I believe this is what has been done.
>
>   However, as a simple example suppose someone wanted to define f(x) as the slope of a chord line on the sine function between x+1 and 1 radians which would be:
>
>  f(x) = (sin(x+1)-sin(1))/x
>
> Using the above operations as they stand loses considerable accuracy near zero.  For example for x = 2^(-26) it will lose about half of the available 52 bits of accuracy, whereas a good polynomial approximation to this function in the vicinity of zero can preserve almost all of them.
>
>   {Note: Of course one could use
>
>  f(x) = (sin(x)*cos(1)-2*sin(x/2)^2*sin(1))/x
>
> which would also preserve full accuracy near, though not exactly at, zero but only because of the above argument in the first paragraph.)
>
> Roger Stafford

What about de l'Hopital's rule:
limit of sin(x)/x as x-> 0 is cos(x)/1 at x=0 i.e 1

Subject: conditional operator

From: Matt J

Date: 8 Nov, 2011 13:17:30

Message: 16 of 28

"Roger Stafford" wrote in message <j8qqvq$i10$1@newscl01ah.mathworks.com>...
>
> Matt J, in general I would tend to agree with the other Matt.
==============

Good point, Roger.

Interestingly, though, both Matt's are the same as it turns out, so I win either way! :-)

I guess I had a change of heart between 2009 and 2010 and didn't recognize my own prior post...

Subject: conditional operator

From: Jim Mutch

Date: 19 Mar, 2013 19:20:19

Message: 17 of 28

"Steven Lord" <slord@mathworks.com> wrote in message
 > MATLAB does not have the ternary ?: operator, but we do have a request in
> the enhancement database for this.

How's this coming?

Since short-circuit evaluation (http://en.wikipedia.org/wiki/Short-circuit_evaluation) is a key part of the ternary operator's usefulness, it can only be efficiently implemented at the language level. We users can't do it for ourselves.

Subject: conditional operator

From: Steven_Lord

Date: 20 Mar, 2013 14:22:13

Message: 18 of 28



"Jim Mutch" <jmutch@mit.edu> wrote in message
news:kiadpj$jd2$1@newscl01ah.mathworks.com...
> "Steven Lord" <slord@mathworks.com> wrote in message
> > MATLAB does not have the ternary ?: operator, but we do have a request
> > in the enhancement database for this.
>
> How's this coming?

It is not part of the recently released release R2013a. Beyond that I can't
comment; I don't discuss whether or not something will be implemented in the
future.

> Since short-circuit evaluation
> (http://en.wikipedia.org/wiki/Short-circuit_evaluation) is a key part of
> the ternary operator's usefulness, it can only be efficiently implemented
> at the language level. We users can't do it for ourselves.

Since you're quoting from the 4th message in this thread:

http://www.mathworks.com/matlabcentral/newsreader/view_thread/147044#369876

I know that you've seen the implementation I wrote in that message. I'm
guessing that didn't satisfy your needs -- what about it didn't?

Also, out of curiosity what would you expect z to contain after executing
the following code , assuming that MATLAB defined the operator using the
syntax (A ? B : C) [which I believe it would not, since the question mark
and COLON already have meanings in MATLAB. The question mark wouldn't be
ambiguous in most (or maybe even any) situations; the colon definitely would
in some common scenarios.(*)]

A = eye(5);
B = magic(5);
C = ones(5);
z = A ? B : C

I can think of three possibilities offhand and I'm curious which one you
expect or whether you expect a 4th.

(*) z = A ? 1:10:11:20; is one such common scenario. I know parentheses can
break that ambiguity in at least four different ways, but I'd prefer not to
get into a situation where they're needed if we don't have to.

--
Steve Lord
slord@mathworks.com
To contact Technical Support use the Contact Us link on
http://www.mathworks.com

Subject: conditional operator

From: Sean Little

Date: 20 Mar, 2013 15:49:05

Message: 19 of 28

"Steven_Lord" <slord@mathworks.com> wrote in message <kicgmk$okd$1@newscl01ah.mathworks.com>...
>
>
> "Jim Mutch" <jmutch@mit.edu> wrote in message
> news:kiadpj$jd2$1@newscl01ah.mathworks.com...
> > "Steven Lord" <slord@mathworks.com> wrote in message
> > > MATLAB does not have the ternary ?: operator, but we do have a request
> > > in the enhancement database for this.
> >
> > How's this coming?
>
> It is not part of the recently released release R2013a. Beyond that I can't
> comment; I don't discuss whether or not something will be implemented in the
> future.
>
> > Since short-circuit evaluation
> > (http://en.wikipedia.org/wiki/Short-circuit_evaluation) is a key part of
> > the ternary operator's usefulness, it can only be efficiently implemented
> > at the language level. We users can't do it for ourselves.
>
> Since you're quoting from the 4th message in this thread:
>
> http://www.mathworks.com/matlabcentral/newsreader/view_thread/147044#369876
>
> I know that you've seen the implementation I wrote in that message. I'm
> guessing that didn't satisfy your needs -- what about it didn't?
>
> Also, out of curiosity what would you expect z to contain after executing
> the following code , assuming that MATLAB defined the operator using the
> syntax (A ? B : C) [which I believe it would not, since the question mark
> and COLON already have meanings in MATLAB. The question mark wouldn't be
> ambiguous in most (or maybe even any) situations; the colon definitely would
> in some common scenarios.(*)]
>
> A = eye(5);
> B = magic(5);
> C = ones(5);
> z = A ? B : C
>
> I can think of three possibilities offhand and I'm curious which one you
> expect or whether you expect a 4th.
>
> (*) z = A ? 1:10:11:20; is one such common scenario. I know parentheses can
> break that ambiguity in at least four different ways, but I'd prefer not to
> get into a situation where they're needed if we don't have to.
>
> --
> Steve Lord
> slord@mathworks.com
> To contact Technical Support use the Contact Us link on
> http://www.mathworks.com

What does the question mark mean in Matlab?

>> help punct

...does not list anything.

Subject: conditional operator

From: Eric Sampson

Date: 20 Mar, 2013 17:22:11

Message: 20 of 28

"Steven_Lord" <slord@mathworks.com> wrote in message <kicgmk$okd$1@newscl01ah.mathworks.com>...
>
(snip)
>
> Also, out of curiosity what would you expect z to contain after executing
> the following code , assuming that MATLAB defined the operator using the
> syntax (A ? B : C) [which I believe it would not, since the question mark
> and COLON already have meanings in MATLAB. The question mark wouldn't be
> ambiguous in most (or maybe even any) situations; the colon definitely would
> in some common scenarios.(*)]
>
> A = eye(5);
> B = magic(5);
> C = ones(5);
> z = A ? B : C
>
> I can think of three possibilities offhand and I'm curious which one you
> expect or whether you expect a 4th.

Hi Steve!! :)

For testing purposes I've defined a function IFF as follows:

function out = iff(cond,vtrue,vfalse)
if cond
    out = vtrue;
else
    out = vfalse;
end

Given that, I would expect the following:

 Z = arrayfun([@(a,b,c) iff(a,b,c)], A, B, C)

Z =

    17 1 1 1 1
     1 5 1 1 1
     1 1 13 1 1
     1 1 1 21 1
     1 1 1 1 9

That seems like the natural interpretation to me; what other possibilities do you have in mind?

>
> (*) z = A ? 1:10:11:20; is one such common scenario. I know parentheses can
> break that ambiguity in at least four different ways, but I'd prefer not to
> get into a situation where they're needed if we don't have to.

At least for me, I don't care what the syntax looks like; since ':' is out of the question as you show above, how about something like 'z = A ? B else C'. Obviously that now overloads 'else', but to me it reads clearly and I'd think that the parser wouldn't have a problem distinguishing the two cases because of the preceding '?' token. Thoughts?

> Steve Lord
> slord@mathworks.com
> To contact Technical Support use the Contact Us link on
> http://www.mathworks.com

Subject: conditional operator

From: Jim Mutch

Date: 20 Mar, 2013 19:30:20

Message: 21 of 28

"Steven_Lord" <slord@mathworks.com> wrote in message <kicgmk$okd$1@newscl01ah.mathworks.com>...

> I know that you've seen the implementation I wrote in that message. I'm
> guessing that didn't satisfy your needs -- what about it didn't?

> Also, out of curiosity what would you expect z to contain after executing
> the following code , assuming that MATLAB defined the operator using the
> syntax (A ? B : C) [which I believe it would not, since the question mark
> and COLON already have meanings in MATLAB. The question mark wouldn't be
> ambiguous in most (or maybe even any) situations; the colon definitely would
> in some common scenarios.(*)]
>
> A = eye(5);
> B = magic(5);
> C = ones(5);
> z = A ? B : C

I assume you mean the QUESTIONCOLON function. What's missing is the short-circuiting of evaluation. In C/C++, when you have the expression (A ? B : C) and A is false, the expression for B is never even *evaluated*. Similarly, if A is true, then the expression for C is never evaluated. This serves two purposes. (1) It saves execution time. (2) It lets you use "?:" to test for conditions under which an expression is invalid, in order to supply an alternative. For scalar inputs (which is all you have in C/C++) this works great. The original question was about sin(x) / x. In C/C++ you could just write:

    y = (x == 0) ? 1 : sin(x) / x;

When (x == 0), the expression sin(x) / x is not even evaluated. (I have read the remarks about numerical instability near 0, and don't really want to get into it. This is just an example. My point is very general.)

QUESTIONCOLON doesn't accomplish this. Both possible values, x1 and x2, get computed before QUESTIONCOLON even starts executing. Then it decides which one to use and which one to throw away. By that point, time has already been expended to compute both values, and any errors/warnings have already occurred.

I don't care about the specific syntax being the same as C/C++; I just want equivalent functionality. I want it to work just like an IF statement, but in a single expression. Maybe even use the same words? For example:

    X = if A then B else C;

This would be semantically equivalent to:

    if A then
        X = B; % only executed if A is true!
    else
        X = C; % only executed if A is false!
    end

Now, I don't see a way of defining something like this for nonscalar inputs that includes short-circuiting. And since short-circuiting is really the only good reason for requesting a language feature, instead of just using something like QUESTIONCOLON, I say don't even try. I want something that works like an IF statement. IF statements aren't vectorized either: I believe if the condition returns a nonscalar result, for an IF statement there is an implicit "any()" around the condition. You go one way or the other, and only once.

Under this definition, the answer to your example is that it would return exactly magic(5).

If anyone can think of a reasonable way to define "?:" for nonscalar inputs that includes short-circuiting I'd be curious to hear it.

Jim

Subject: conditional operator

From: Steven_Lord

Date: 20 Mar, 2013 20:00:41

Message: 22 of 28



"Sean Little" <sanborne@fastmail.fm> wrote in message
news:kiclph$cn2$1@newscl01ah.mathworks.com...
> "Steven_Lord" <slord@mathworks.com> wrote in message
> <kicgmk$okd$1@newscl01ah.mathworks.com>...

*snip*

> What does the question mark mean in Matlab?

http://www.mathworks.com/help/matlab/ref/metaclass.html

It allows you to get some advanced information about a class if you just
have the name of the class. This is handy for getting that advanced
information about an abstract class like HGSETGET, which by definition you
cannot instantiate.

>>> help punct
>
> ...does not list anything.

It probably should; I'll note that to the documentation staff.

--
Steve Lord
slord@mathworks.com
To contact Technical Support use the Contact Us link on
http://www.mathworks.com

Subject: conditional operator

From: Steven_Lord

Date: 20 Mar, 2013 20:27:02

Message: 23 of 28



"Jim Mutch" <jmutch@mit.edu> wrote in message
news:kid2oc$r51$1@newscl01ah.mathworks.com...
> "Steven_Lord" <slord@mathworks.com> wrote in message
> <kicgmk$okd$1@newscl01ah.mathworks.com>...
>
>> I know that you've seen the implementation I wrote in that message. I'm
>> guessing that didn't satisfy your needs -- what about it didn't?
>
>> Also, out of curiosity what would you expect z to contain after executing
>> the following code , assuming that MATLAB defined the operator using the
>> syntax (A ? B : C) [which I believe it would not, since the question mark
>> and COLON already have meanings in MATLAB. The question mark wouldn't be
>> ambiguous in most (or maybe even any) situations; the colon definitely
>> would in some common scenarios.(*)]
>>
>> A = eye(5);
>> B = magic(5);
>> C = ones(5);
>> z = A ? B : C
>
> I assume you mean the QUESTIONCOLON function.

Yes.

> What's missing is the short-circuiting of evaluation.

No.

> In C/C++, when you have the expression (A ? B : C) and A is false, the
> expression for B is never even *evaluated*. Similarly, if A is true, then
> the expression for C is never evaluated. This serves two purposes. (1)
> It saves execution time. (2) It lets you use "?:" to test for conditions
> under which an expression is invalid, in order to supply an alternative.
> For scalar inputs (which is all you have in C/C++) this works great. The
> original question was about sin(x) / x. In C/C++ you could just write:
>
> y = (x == 0) ? 1 : sin(x) / x;
>
> When (x == 0), the expression sin(x) / x is not even evaluated. (I have
> read the remarks about numerical instability near 0, and don't really want
> to get into it. This is just an example. My point is very general.)
>
> QUESTIONCOLON doesn't accomplish this. Both possible values, x1 and x2,
> get computed before QUESTIONCOLON even starts executing. Then it decides
> which one to use and which one to throw away. By that point, time has
> already been expended to compute both values, and any errors/warnings have
> already occurred.

Well, yes, x1 and x2 need to be evaluated since they're input arguments to
QUESTIONCOLON and so we need to know what to put in its workspace. But no,
no errors will be thrown or warnings issued unless you define the inputs
incorrectly. Let me copy that function and its help text here for reference.


function y = questioncolon(condition, x1, x2)
% QUESTIONCOLON M-file for C's ?: ternary operator
% Syntax: y = questioncolon(condition, x1, x2)
%
% The elements of the output matrix will be set as:
% y(condition==true) = x1(condition==true)
% y(condition==false) = x2(condition==false)
%
% x1 and x2 can be function handles or matrices the same size as condition
%
% Example:
% x = -10:10;
% y = questioncolon(x==0, @(z) 1, @(z) sin(x(z))./x(z));

y = zeros(size(condition));
y(condition) = x1(condition);
y(~condition) = x2(~condition);


In the example, note that the second and third inputs to QUESTIONCOLON are
_anonymous functions_ not numeric arrays. If you use that syntax yes, MATLAB
will need to construct those anonymous functions as part of calling the
function. But it will NOT call SIN or perform the division until the last
line of the function and will ONLY call SIN and perform the division for
those elements of x where (x == 0) is false (i.e. x ~= 0). If all the
elements of x are zero, that's going to be a pretty quick calculation. It's
not exactly short-circuiting, but it's pretty close.

x = zeros(1, 1e6);
z = ~(x == 0);
tic;
    sin(x(z))./x(z);
toc

> I don't care about the specific syntax being the same as C/C++; I just
> want equivalent functionality. I want it to work just like an IF
> statement, but in a single expression. Maybe even use the same words?
> For example:
>
> X = if A then B else C;

That's already valid MATLAB syntax if you remove the then and add some
commas, though it's not a single expression (and so is not eligible to be
used in an anonymous function.)

> This would be semantically equivalent to:
>
> if A then
> X = B; % only executed if A is true!
> else
> X = C; % only executed if A is false!
> end
>
> Now, I don't see a way of defining something like this for nonscalar
> inputs that includes short-circuiting. And since short-circuiting is
> really the only good reason for requesting a language feature, instead of
> just using something like QUESTIONCOLON, I say don't even try. I want
> something that works like an IF statement. IF statements aren't
> vectorized either: I believe if the condition returns a nonscalar result,
> for an IF statement there is an implicit "any()" around the condition.
> You go one way or the other, and only once.

ALL, not ANY.

> Under this definition, the answer to your example is that it would return
> exactly magic(5).

Given that IF does ALL, I think it's safe to amend your respond to ones(5)
since not ALL the elements of A are nonzero. But yes, that's one
possibility.

> If anyone can think of a reasonable way to define "?:" for nonscalar
> inputs that includes short-circuiting I'd be curious to hear it.

Eric Sampson posted the second possibility in his message, using elements of
B corresponding to true elements in the condition and elements of C
corresponding to false elements in the condition. If this hypothetical
ternary operator behaved this way, it may be reasonable that if ALL the
elements in the condition were true or false we could skip executing the
other piece entirely.

The third possibility I thought of would be to do what the short-circuit AND
and OR operators do. Compare

thisWorks = (1:10 == 5) | (1:10 == 7) % non-short-circuiting
thisDoesNotWork = (1:10 == 5) || (1:10 == 7) % short-circuiting

http://www.mathworks.com/help/matlab/ref/or.html

That may be a wee bit too strict, though.

--
Steve Lord
slord@mathworks.com
To contact Technical Support use the Contact Us link on
http://www.mathworks.com

Subject: conditional operator

From: Jim Mutch

Date: 20 Mar, 2013 22:16:06

Message: 24 of 28

"Steven_Lord" <slord@mathworks.com> wrote in message <kid62m$997$1@newscl01ah.mathworks.com>...

> In the example, note that the second and third inputs to QUESTIONCOLON are
> _anonymous functions_ not numeric arrays. If you use that syntax yes, MATLAB
> will need to construct those anonymous functions as part of calling the
> function. But it will NOT call SIN or perform the division until the last
> line of the function and will ONLY call SIN and perform the division for
> those elements of x where (x == 0) is false (i.e. x ~= 0). If all the
> elements of x are zero, that's going to be a pretty quick calculation. It's
> not exactly short-circuiting, but it's pretty close.

I see your point -- it should usually be possible to do something like that. I just don't want to. :) I don't want to have to define more anonymous functions like this. This whole thread is admittedly about syntactic sugar. Everybody can already do what they want to, the question is, how easily? If there was a real ternary operator like I described, I would use it _all_ the time! Not just in function definitions. I would use it in sections of code where I check parameters, initialize things, etc. Like this:
  x = isfield(s, 'x') ? s.x : 3;
That's only one of many examples. Again, I can already do what I need with what MATLAB already has. I just want it to be nicer looking. A ternary operator would really help.

> > X = if A then B else C;
>
> That's already valid MATLAB syntax if you remove the then and add some
> commas, though it's not a single expression (and so is not eligible to be
> used in an anonymous function.)

I'm not sure what you mean there.

> > I believe if the condition returns a nonscalar result,
> > for an IF statement there is an implicit "any()" around the condition.
> > You go one way or the other, and only once.
>
> ALL, not ANY.

Oops, right.

> Given that IF does ALL, I think it's safe to amend your respond to ones(5)
> since not ALL the elements of A are nonzero.

Right.

> If this hypothetical
> ternary operator behaved this way, it may be reasonable that if ALL the
> elements in the condition were true or false we could skip executing the
> other piece entirely.

Sounds nice!

Jim

Subject: conditional operator

From: Eric Sampson

Date: 21 Mar, 2013 00:06:14

Message: 25 of 28

"Steven_Lord" <slord@mathworks.com> wrote in message <kid62m$997$1@newscl01ah.mathworks.com>...
>
(snip discussion about ternary operator)
> --

Hi Steve, the other thing it would be nice to have in this hypothetical ternary operator would be scalar expansion for B and/or C. Does that make sense?

Eric

Subject: conditional operator

From: Eric Sampson

Date: 23 Mar, 2013 21:44:06

Message: 26 of 28

"Steven_Lord" <slord@mathworks.com> wrote in message <kid62m$997$1@newscl01ah.mathworks.com>...
>
(snip)
> > Now, I don't see a way of defining something like this for nonscalar
> > inputs that includes short-circuiting. And since short-circuiting is
> > really the only good reason for requesting a language feature, instead of
> > just using something like QUESTIONCOLON, I say don't even try. I want
> > something that works like an IF statement. IF statements aren't
> > vectorized either: I believe if the condition returns a nonscalar result,
> > for an IF statement there is an implicit "any()" around the condition.
> > You go one way or the other, and only once.
>
> ALL, not ANY.
>
> > Under this definition, the answer to your example is that it would return
> > exactly magic(5).
>
> Given that IF does ALL, I think it's safe to amend your respond to ones(5)
> since not ALL the elements of A are nonzero. But yes, that's one
> possibility.
>
> > If anyone can think of a reasonable way to define "?:" for nonscalar
> > inputs that includes short-circuiting I'd be curious to hear it.
>
> Eric Sampson posted the second possibility in his message, using elements of
> B corresponding to true elements in the condition and elements of C
> corresponding to false elements in the condition. If this hypothetical
> ternary operator behaved this way, it may be reasonable that if ALL the
> elements in the condition were true or false we could skip executing the
> other piece entirely.
>
> The third possibility I thought of would be to do what the short-circuit AND
> and OR operators do. Compare
>
> thisWorks = (1:10 == 5) | (1:10 == 7) % non-short-circuiting
> thisDoesNotWork = (1:10 == 5) || (1:10 == 7) % short-circuiting
>
> http://www.mathworks.com/help/matlab/ref/or.html
>
> That may be a wee bit too strict, though.
>

Steve, what do you think about this suggestion:

Z = A ? B else C % returns elements of B and C according to elements of A.
Z = A ?? B else C % returns either B or C based on test of all(A).

Cheers

Subject: conditional operator

From: Steven_Lord

Date: 25 Mar, 2013 14:55:28

Message: 27 of 28



"Eric Sampson" <ericDOTsampson@gmail.com> wrote in message
news:kil7n6$m9p$1@newscl01ah.mathworks.com...
> "Steven_Lord" <slord@mathworks.com> wrote in message
> <kid62m$997$1@newscl01ah.mathworks.com>...

*snip*

> Steve, what do you think about this suggestion:
>
> Z = A ? B else C % returns elements of B and C according to elements of A.
> Z = A ?? B else C % returns either B or C based on test of all(A).

I'll make sure that the entry in the enhancement database is updated to
indicate the further discussions and suggestions that have happened in the
thread in the past week.

--
Steve Lord
slord@mathworks.com
To contact Technical Support use the Contact Us link on
http://www.mathworks.com

Subject: conditional operator

From: Eric Sampson

Date: 25 Mar, 2013 15:46:09

Message: 28 of 28

"Steven_Lord" <slord@mathworks.com> wrote in message <kipoh0$eb1$1@newscl01ah.mathworks.com>...
>
> (snip)
> I'll make sure that the entry in the enhancement database is updated to
> indicate the further discussions and suggestions that have happened in the
> thread in the past week.
>
> --

Thanks Steve!!

Tags for this Thread

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us