How can I create a piecewise inline function in MATLAB?

前端 未结 4 582
夕颜
夕颜 2021-01-05 07:04

I have a function in MATLAB which takes another function as an argument. I would like to somehow define a piecewise inline function that can be passed in. Is this somehow po

4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-05 07:36

    I just had to solve that problem, and I think the easiest thing to do is use anonymous functions. Say that you have a piecewise function:

    when x<0    : x^2 + 3x
    when 0<=x<=4: e^x
    when x>4    : log(x)
    

    I'd first define logical masks for each piecewise region:

    PIECE1 = @(x) x<0
    PIECE2 = @(x) x>=0 & x<=4
    PIECE3 = @(x) x>4
    

    Then I'd put them all together:

    f = @(x) PIECE1(x).*(x.^2+3*x) + PIECE2(x).*exp(x) + PIECE3(x).*log(x)
    
    x = -10:.1:10
    figure;
    plot(x,f(x))
    

提交回复
热议问题