Using for loops for a summation of data

조회 수: 1 (최근 30일)
Jared Martin
Jared Martin 2015년 4월 22일
답변: Image Analyst 2015년 4월 22일
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?

답변 (1개)

Image Analyst
Image Analyst 2015년 4월 22일
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);
end
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.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by