Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

MATLAB sum loop issue

  1. Feb 18, 2016 #1
    So i want to calculate an r value 5 different times then find the mean of the 5 calculated values.
    I have 2,187 data points. the first line of code generates 100 random points 1-2187.
    The code has a bug but my major issue is it calculates r then loops again calculates r, loops again calculates r and there is no way to sum this. How can I edit my code.

    for i = 1:5
    randomdata = round(rand(100,1).*2187);

    xval = x(randomdata);
    yval = y(randomdata);
    numerator = length(xval)*nansum(xval.*yval) - (nansum(xval)*nansum(yval));

    xsumsquared = nansum(xval)^2;
    ysumsquared = nansum(yval)^2;
    dddx = sqrt(length(xval)*nansum(xval.^2) - xsumsquared);
    ddy = sqrt(length(xval)*nansum(yval.^2) - ysumsquared);
    demonator = dddx * ddy;
    r = numerator/demonator;


  2. jcsd
  3. Feb 18, 2016 #2


    User Avatar
    Science Advisor
    Gold Member
    2017 Award

    Set a variable sum_r =0; before all your code. Total sum_r = sum_r + r; right after r is calculated. Display sum_r after your code.
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook