Defining piecewise function in matlab

Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
1 reply · 9K views
tmpr
Messages
5
Reaction score
0
How would you write piecewise functions in MATLAB that can take vector inputs?

Here's a function that I'm trying to write.
Code:
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.
 
Physics news on Phys.org
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)