Register to reply

Defining piecewise function in matlab

by tmpr
Tags: defining, function, matlab, piecewise
Share this thread:
tmpr
#1
Oct27-10, 12:46 AM
P: 5
How would you write piecewise functions in matlab that can take vector inputs?

Here's a function that I'm trying to write.
function y=g(x)
if x==0
    y=1;
else
y=sin(x)./x;
end
If I call g([0,pi/2]), I want it to return [0,2/pi], but what I get instead is [NaN,2/pi]. I'm guessing when I write x==0, matlab is comparing the entire input to 0.
Phys.Org News Partner Science news on Phys.org
'Smart material' chin strap harvests energy from chewing
King Richard III died painfully on battlefield
Capturing ancient Maya sites from both a rat's and a 'bat's eye view'
matematikawan
#2
Nov3-10, 12:30 AM
P: 333
Try this to eliminate the problem at x=0.


g = @(x) 1.*(x==0) + (x~=0).*sin(x)./(x+(x==0));
t=[0 pi/2];
g(t)


Register to reply

Related Discussions
MATLAB - piecewise defined Fn as periodic Engineering, Comp Sci, & Technology Homework 1
Defining implicit function given a parametric function Calculus & Beyond Homework 1
Finding constants in a piecewise function that allow the function to be differentiabl Calculus & Beyond Homework 5
We need help on piecewise function... General Math 11
Piecewise function Calculus 1