Creating Anonymous Functions for Complex Functions

  • Context: MATLAB 
  • Thread starter Thread starter matematikawan
  • Start date Start date
  • Tags Tags
    Complex Functions
Click For Summary
SUMMARY

This discussion focuses on creating anonymous functions in MATLAB for complex piecewise functions. The user demonstrates how to define a simple anonymous function for integration using the syntax myfun=@(x) x.^2 + x; and the quad function. They seek to create an anonymous function for a piecewise function defined as f(x)=\left\{\begin{array}{ccc}x,& 0 \leq x <1\\ 1-x, & 1 \leq x <2\\ 0 , & elsewhere \end{array}\right.. The solution provided is f = @(x) x.*(0<=x & x<1) + (1-x).*(1<=x & x<=2);, effectively demonstrating the use of logical indexing in MATLAB.

PREREQUISITES
  • Familiarity with MATLAB syntax and functions
  • Understanding of anonymous functions in MATLAB
  • Knowledge of piecewise functions
  • Basic experience with logical indexing in MATLAB
NEXT STEPS
  • Explore advanced MATLAB anonymous functions
  • Learn about MATLAB logical indexing techniques
  • Study MATLAB's quad function for numerical integration
  • Investigate piecewise function implementations in MATLAB
USEFUL FOR

MATLAB users, data analysts, and engineers looking to streamline their code by using anonymous functions for complex mathematical expressions.

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
[tex] f(x)=\left\{\begin{array}{ccc}x,&\mbox{ } 0 \leq x <1\\<br /> 1-x, & \mbox{ } 1 \leq x <2\\<br /> 0 , & \mbox{ elsewhere } \end{array}\right.[/tex]

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