0

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.

TIA

Adam
  • 2,726
  • 1
  • 9
  • 22
user2587726
  • 169
  • 2
  • 11

1 Answers1

2
  • f is a function but its type is cfit not function handle.

  • integral() function requires function handle, what you can do is transform cfit into function handle before taking the integral

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 :

  • a
  • b
  • c
  • d
  • k

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.


Adam
  • 2,726
  • 1
  • 9
  • 22
  • Thanks for this, I have 2 questions though: 1) Why can't I plot f once I've turned it in to a function handle? It works before that line I just don't think I understand function handles properly. 2) What does the ... 'Array valued', 1) do as well? It didn't work till I put that in so it must do something... – user2587726 Jun 17 '19 at 13:05