Search code examples
arraysmatlabnumerical-integration

User defined script for trapezoidal rule for data in an array in Matlab


I am supposed to integrate data of acceleration and time to get velocity using a user defined script.

What I have so far is:

function myIntegral=myCumulativeTrapz(X,Y)
myIntegral=0.5*(Y+(Y+1))*((X+1)-X)

When I hit run, I get this error:

Error: File: myCumulativeTrapz.m Line: 27 Column: 1

Function definitions are not permitted in this context.

If the script for integration was successful, I would then put

velocity=myCumulativeTrapz(data_resultant_acc(:,1), data_resultant_acc(:,2))

in the command window. (Data_resultant_acc is an array where time is in the first column and acceleration is in the second column.)

Can someone help me out and tell me why is this not working?


Solution

  • The error message is shown because Matlab file can't contain both functions and commands that are outside of any functions. So, if you have something like

    data_resultant_acc = rand(10,2);
    velocity=myCumulativeTrapz(data_resultant_acc(:,1), data_resultant_acc(:,2));
    
    function myIntegral=myCumulativeTrapz(X,Y)
      myIntegral=0.5*(Y+(Y+1))*((X+1)-X)
    end 
    

    change that to

    function myProject
      data_resultant_acc = rand(10,2);
      velocity=myCumulativeTrapz(data_resultant_acc(:,1), data_resultant_acc(:,2));
    end
    
    function myIntegral=myCumulativeTrapz(X,Y)
      myIntegral=0.5*(Y+(Y+1))*((X+1)-X)
    end 
    

    thus making myProject the top-level function that will be executed when you run the file (for best results, the file name should be the name of that function).

    After that, you will discover that 0.5*(Y+(Y+1))*((X+1)-X) is not a valid formula, for multiple reasons. Since both X and Y are column vectors, the first one should be transposed before multiplication. Also, you are adding 1 to vector components instead of shifting index by 1. A correct way to do the index shift is below:

     myIntegral=0.5*(Y(1:end-1)+Y(2:end))'*(X(2:end)-X(1:end-1));
    

    Here the comma selectors create vectors that omit either the very first or the very last entry. The average of two such vectors gives the averages of adjacent values. The difference gives the difference of adjacent values.