Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: Properly vectorizing code when using "if"
Date: Sun, 12 Oct 2008 00:54:02 +0000 (UTC)
Organization: The MathWorks Inc
Lines: 35
Message-ID: <gcrhra$j53$1@fred.mathworks.com>
References: <gcrab9$kns$1@fred.mathworks.com> <gcrdvi$m08$1@fred.mathworks.com>
Reply-To: <HIDDEN>
NNTP-Posting-Host: webapp-02-blr.mathworks.com
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1223772842 19619 172.30.248.37 (12 Oct 2008 00:54:02 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Sun, 12 Oct 2008 00:54:02 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 222043
Xref: news.mathworks.com comp.soft-sys.matlab:494730


Another a little more elegant

r = x .^ (2+(x<=0));

Lucio

"Donn Shull" <donn.shull.no_spam@aetoolbox.com> wrote in message <gcrdvi$m08$1@fred.mathworks.com>...
> one solution is to use logical operators:
> 
> r = ((x>0).*x.*x) + ((x<=0).*x.*x.*x);
> 
> Hope this helps,
> 
> Donn
> 
> "Johan " <robert.mchugh@ips.invensys.com> wrote in message <gcrab9$kns$1@fred.mathworks.com>...
> > Is it possible to "vectorize" an if statement?
> > 
> > For example, in the example below, would like to use y = x^2 when x is less than 0 and y = x^3 when x is greater than zero.  Both of these functions are positive in their respective domains. However, the implementation below doesn't work as intended.  
> > 
> > Any recommendations? 
> > Thanks. 
> > 
> > x = -1:0.01:1;
> > r = ifTest(x);
> > plot(x,r);
> > 
> > function[ifTest] = ifTest(x)
> > 
> > if (x < 0 )
> >    r = x .* x;
> > else
> >    r = x .* x .* x;
> > end
> > ifTest = r;