How to summation using for loop with a vector
Show older comments
This is the data used for xi and yi, i have gotten x bar and y bar already, not to sure how to make a for loop for SXY and SXX
x = normrnd(10, 1, 1, 100);
y = 1 + 2 .* x + normrnd(0, 1, 1, 100);
my attempt
SXY = 0;
for [i = 100]
SXY = SXY + (( x(i) - xBar) * ( y(i) - yBar));
end
not sure how to correctly code x(i) and y(i) which should be a new value form the array every time it loops

Accepted Answer
More Answers (1)
"... not to sure how to make a for loop for SXY ..."
The square brackets give you a syntax error:
for [i = 100]
Removing them and using the following expression would execute the loop one time, with value i = 100:
for i = 100
To execute the loop 100 times, with values i = 1, i = 2, ..., i = 100, instead, you should do this:
for i = 1:100
Or better:
for i = 1:numel(x)
Once you change the for line, the rest of the code looks like it will work.
However, you don't need to use a for loop to do it. This does the same thing:
SXY = sum(( x - xBar) .* ( y - yBar)) % note: using .* for element-wise multiplication
Categories
Find more on Creating, Deleting, and Querying Graphics Objects 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!