MATLAB Creating Anonymous Functions for Complex Functions

  • Thread starter Thread starter matematikawan
  • Start date Start date
  • Tags Tags
    Complex Functions
AI Thread Summary
Creating anonymous functions in MATLAB can simplify coding for straightforward functions without the need for separate m-files. For the piecewise function defined as f(x) = x for 0 ≤ x < 1, 1 - x for 1 ≤ x < 2, and 0 elsewhere, it is possible to represent it as an anonymous function. The expression f = @(x) x.*(0<=x & x<1) + (1-x).*(1<=x & x<=2) effectively captures the required functionality. This approach allows for efficient integration and manipulation of piecewise functions directly within MATLAB scripts.
matematikawan
Messages
336
Reaction score
0
I normally create anonymous function in order to avoid creating extra m-file if the function is simple enough. For example if I want to integrate the function f(x)=x2+x, I just write a simple MATLAB script like

myfun=@(x) x.^2 + x;
quad(myfun,0,1)


But how do we create an anonymous function for the following function
<br /> f(x)=\left\{\begin{array}{ccc}x,&amp;\mbox{ } 0 \leq x &lt;1\\<br /> 1-x, &amp; \mbox{ } 1 \leq x &lt;2\\<br /> 0 , &amp; \mbox{ elsewhere } \end{array}\right.<br />

The function look simple to me and I know how to write a function m-file for it. But I want to avoid it. Is it possible to create an anonymous function for it?
 
Physics news on Phys.org
Here you go.
Code:
f = @(x) x.*(0<=x & x<1) + (1-x).*(1<=x & x<=2);
 
Thanks a lot matonski. This is really :cool:
 
Last edited:

Similar threads

Replies
18
Views
2K
Replies
4
Views
1K
Replies
1
Views
2K
Replies
3
Views
2K
Replies
8
Views
3K
Back
Top