Path: news.mathworks.com!not-for-mail
From: "Donn Shull" <donn.shull.no_spam@aetoolbox.com>
Newsgroups: comp.soft-sys.matlab
Subject: Re: Properly vectorizing code when using "if"
Date: Sat, 11 Oct 2008 23:48:02 +0000 (UTC)
Organization: L &#38; D Engineering LLC
Lines: 28
Message-ID: <gcrdvi$m08$1@fred.mathworks.com>
References: <gcrab9$kns$1@fred.mathworks.com>
Reply-To: "Donn Shull" <donn.shull.no_spam@aetoolbox.com>
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 1223768882 22536 172.30.248.37 (11 Oct 2008 23:48:02 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Sat, 11 Oct 2008 23:48:02 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 219306
Xref: news.mathworks.com comp.soft-sys.matlab:494723


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;