MATLAB Solving MATLAB Sum Loop Issue with 2,187 Data Points

AI Thread Summary
To calculate the mean of five r values derived from a dataset of 2,187 points, the current code generates 100 random indices and computes the correlation coefficient r in a loop. However, it lacks a mechanism to accumulate the r values for averaging. To resolve this, a variable named sum_r should be initialized to zero before the loop begins. After each calculation of r, the value should be added to sum_r. Finally, after the loop, the mean can be calculated by dividing sum_r by 5. This adjustment will allow for the correct summation and averaging of the r values.
Tone L
Messages
72
Reaction score
7
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;


end

thanks
 
Physics news on Phys.org
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.
 
  • Like
Likes Tone L

Similar threads

Replies
1
Views
1K
Replies
10
Views
3K
Replies
7
Views
1K
Replies
4
Views
2K
Replies
8
Views
3K
Replies
8
Views
2K
Back
Top