matlabnumerical-integrationlinear-interpolation

Matlab integrate of fitted "linearinterp" returning error "First input argument must be a function handle"


Trying to get the integral of some experimentally collected data.

After using the envelope and abs functions I'm using the fit function to get the equation I wish to integrate (unfortunately 'poly' isn't giving a close enough fit to the data):

[yupper,ylower] = envelope(signal,1000,'peak');

dat = abs(yupper);

f = fit(x,dat,'linearinterp');

Then when I try

q = integral(f,3e4,9e4);

I get the error:

Error using integral (line 82) First input argument must be a function handle.

Error in findenergyfromfitcurve (line 10) q = integral(f,3e4,9e4);

I thought f was a (mathematical) function, don't understand what the error is telling me. When I try using 'poly3' incase it's the linearinterp messing things up I still get that error.


Solution

  • The code is as follows

    x = rand(5,1);
    dat = rand(5,1);
    f = fit(x,dat,'linearinterp');
    
    % Create a new function handle
    f = @(x)f(x);
    
    q = integral(f, 3e4,9e4,  'ArrayValued', 1)
    
    

    2) What does the ... 'Array valued', 1) do as well? It didn't work till I put that in so it must do something

    f is a piecewise function, the following illustration is based on the assumption that f is a 2-piecewise linear function, but it can be used for n-piecewise function as well. enter image description here

    The task for fit() function is finding the parameters :


    In terms of code f looks like

    function y = f(x,a,b,c,d,k)
        % PIECEWISELINE   A line made of two pieces
        % that is not continuous.
    
        y = zeros(size(x));
    
        % This example includes a for-loop and if statement
        % purely for example purposes.
        for i = 1:length(x)
            if x(i) < k
                y(i) = a.* x(i) + b;
            else
                y(i) = c.* x(i) + d;
            end
        end
    end
    

    To plot a function handle, just use fplot(f)

    Here is the graph for f enter image description here


    To sum up, f probably has more than one expression, that's why I set 'ArrayValued' to true so that integral() function knowns f has more than one expression, omitting it means f has a single expression which is not true.