Search code examples
matlabaveragenon-linear

Find average value of variable in an interval in MATLAB


I have some data inside MATLAB. On the picture you can see a small portion:-

enter image description here

The numbers I'm interested in are RPM and Lambda. As you can see, they are neither strictly decreasing or increasing (they are non-linear so to speak). I want to find the average Lambda value in RPM intervals, like from 250-500, 500-750, 1000-1250 and so on. But I don't know how to write such code in MATLAB and the reason is that I won't know at what index this will happen, because the RPM numbers aren't strictly decreasing/increasing.

while RPM >= 1000 && RPM < 1250
    Lambda_avg = sum of Lambda values in interval / number of Lambdas in interval
end

while RPM >= 1250 && RPM < 1500
...
end

I could maybe sort the RPM-column from lowest to highest, and then also sort the Lambda-column accordingly, although I'm not sure how to do that either.

Is there any way I can find the average lambda-value in a certain RPM interval across all of the data? I hope my question is clear enough.


Solution

  • If you have all the values of lambda in the variable lambda and all the values of RPM in the RPM variable, then you just do, for example

    RPM1 = 1000;
    RPM2 = 1500;
    lambda_avg = mean(lambda((RPM >= RPM1) & (RPM < RPM2)));
    

    A single & does an element-by-element AND comparison, and a single | does the elementwise OR.

    If your data is organized as a MATLAB Table called data, for example, then you can do

    lambda_avg = mean(data.lambda((data.RPM >= RPM1) & (data.RPM < RPM2)));
    

    This method takes advantage of the logical indexing feature of MATLAB, and allows you to skip the loop that you attempted writing in your question...

    Just for reference, if you want to explicitly write a loop to calculate this mean, you can do it like this:

    lambda_avg = 0;
    n_lambda = 0; % number of lambdas you found in the interval
    for i = 1:numel(RPM)
        if (RPM(i) >= RPM1) && (RPM(i) < RPM2)
            lambda_avg = lambda_avg + lambda(i);
            n_lambda = n_lambda + 1;
        end
    end
    lambda_avg = lambda_avg / n_lambda;