How to summation using for loop with a vector
3 views (last 30 days)
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

0 Comments
Accepted Answer
Torsten
on 29 Aug 2022
rng('default')
n = 100;
x = normrnd(10, 1, 1, n);
y = 1 + 2 .* x + normrnd(0, 1, 1, n);
xbar = mean(x)
ybar = mean(y)
sxy = cov(x,y)*(n-1)
sxy = sxy(2,1)
sxx = var(x)*(n-1)
0 Comments
More Answers (1)
Voss
on 29 Aug 2022
Edited: Voss
on 29 Aug 2022
"... 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
0 Comments
See Also
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!