Defining piecewise function in matlab

Click For Summary
SUMMARY

The discussion focuses on defining piecewise functions in MATLAB that can handle vector inputs effectively. A user initially attempted to create a function that returns specific values for zero and non-zero inputs but encountered issues with NaN results when using vector inputs. The solution provided utilizes an anonymous function with logical indexing to correctly handle the case when x equals zero, ensuring that the function returns the expected output of [0, 2/pi] for the input [0, pi/2].

PREREQUISITES
  • Understanding of MATLAB syntax and functions
  • Familiarity with vector operations in MATLAB
  • Knowledge of piecewise function definitions
  • Basic understanding of logical indexing in MATLAB
NEXT STEPS
  • Explore MATLAB anonymous functions for concise function definitions
  • Learn about logical indexing techniques in MATLAB
  • Research MATLAB vectorization methods to optimize performance
  • Study the implementation of more complex piecewise functions in MATLAB
USEFUL FOR

MATLAB users, data analysts, and engineers looking to implement piecewise functions for vectorized calculations in their projects.

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
2K
  • · Replies 1 ·
Replies
1
Views
5K
  • · Replies 1 ·
Replies
1
Views
3K
  • · Replies 11 ·
Replies
11
Views
3K
  • · Replies 2 ·
Replies
2
Views
3K
  • · Replies 18 ·
Replies
18
Views
3K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 1 ·
Replies
1
Views
3K
  • · Replies 4 ·
Replies
4
Views
3K