Using for loops for a summation of data

5 views (last 30 days)
Jared Martin
Jared Martin on 22 Apr 2015
Answered: Image Analyst on 22 Apr 2015
If I am given a data set of: x0= 20 , x1= 27 , x2= 48 and y0= 12 , y1= 26 , y2= 54 and the summation equation:
m=(Summation from k=0 to N-1 for X sub k)(Summation from k=0 to N-1 for Y sub k) - N(Summation from k=0 to N-1 for X sub k * Y sub k)
How would I use for loops in order to sum all of this data to compute the one value for m?

Answers (1)

Image Analyst
Image Analyst on 22 Apr 2015
There is no 0 index so I suspect you should just sum the entire array. Here's a hint - use the sum() function:
theSumX = sum(X);
theSumXY = sum(X .* Y);
If you really need to use a loop instead of sum(), then do something like this
theSum = 0;
for k = 1 : length(x)
theSum = theSum + x(k);
I hope that didn't give too much away. Actually it's just basic programming like you learned in your first programming class. You've probably seen it before and just forgot. Finding the sum, or the max or min, via a for loop is about as basic/trivial as you can get.


Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!