Search code examples
matlaboctaveoctave-gui

What is the canonical way to integrating an array over another


consider the two arrays:

x = [0 .05 .1 .3 .32 .4 .55 .7 1 1.3 1.4 1.45 1.6 1.8 1.9 2 2.2 2.3 2.6 2.8 2.91 3];
y = x.^2;

I want to integrate y over x. So far, I have figured out that I can use the trapz() function in a for loop:

y1 = zeros(length(x));

for ii = 1:length(x)
    y1(ii) = trapz(x(1:ii), y(1:ii));
end

plot(x, y1, x, y);

However, I wondered if there is a canonical way to do this without using a for loop.

P.S.1. I suppose MATLAB/Octave are vectorized functions, and there should be predefined functions to take care of this sort of stuff.

P.S.2. I do not own a MATLAB license now, but the answer must be compatible with both MATLAB and Octave.


Solution

  • Sounds like you want the cumtrapz( ) function:

    y1 = zeros(length(x), 1);
    
    y1 = cumtrapz(x, y)
    plot(x, y1, x, y);