Search code examples
matlabanonymous-functionderivative

Matlab derivative returns a constant


I defined a function which returns the derivative of either a symbolic expression or a function handle (plus a few more).

function df = der(f)
    if isa(f, 'cfit') || isa(f, 'sfit')
        df = @(x) differentiate(f, x);
    elseif isa(f, 'sym') || isa(f, 'function_handle')
        syms r
        F = sym(f);
        df = matlabFunction(diff(F), 'Vars', r);
    else
        error('Not a derivative of a known type')
    end
end

It works well however when I feed in a line, I get something which does not produce arrays.

>> df = der(@(r) r)

df = 

    @(r)1.0

>> df([1,2,3])

ans =

    1

Is there anyway to catch whether the output function is a constant and change the output so the behavior is,

>> df = der(@(r) r)

df = 

    @(r)1.0*ones(size(r))

>> df([1,2,3])

ans =

    1 1 1

Solution

  • Here's one solution.

    function df = der(f)
        if isa(f, 'cfit') || isa(f, 'sfit')
            df = @(x) differentiate(f, x);
        elseif isa(f, 'sym') || isa(f, 'function_handle')
            syms r
            F = sym(f);
            df = matlabFunction(diff(F), 'Vars', r);
        % These next four lines have been added:
            c = df(ones(1,2));             
            if length(c) == 1
                df = @(x) c*ones(size(x));
            end                            
        else
            error('Not a derivative of a known type')
        end
    end
    

    Evaluating df = der(@(r) 20*r); df([1,2,3]) now gives the output

    ans =
    
        20 20 20