MATLAB Defining piecewise function in matlab

Click For Summary
The discussion focuses on writing piecewise functions in MATLAB that can handle vector inputs. The original function, designed to return specific values for x=0 and sin(x)/x otherwise, encounters an issue where calling it with a vector input results in NaN for the zero element. This occurs because MATLAB evaluates the condition x==0 for the entire vector rather than element-wise. A proposed solution uses an anonymous function that incorporates logical indexing to handle the zero case effectively. The revised function uses the expression 1.*(x==0) to return 1 when x is 0 and sin(x)/(x+(x==0)) to avoid division by zero, allowing the function to return the expected output for vector inputs. The example provided demonstrates the function's correct behavior with the input [0, pi/2], yielding [1, 2/pi].
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)
 

Similar threads

  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 4 ·
Replies
4
Views
1K
  • · Replies 1 ·
Replies
1
Views
5K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 11 ·
Replies
11
Views
3K
  • · Replies 2 ·
Replies
2
Views
3K
  • · Replies 5 ·
Replies
5
Views
2K
  • · Replies 18 ·
Replies
18
Views
3K
  • · Replies 1 ·
Replies
1
Views
3K
  • · Replies 4 ·
Replies
4
Views
3K