How to summation using for loop with a vector

3 views (last 30 days)
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

Torsten
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)
xbar = 10.1231
ybar = mean(y)
ybar = 21.1735
sxy = cov(x,y)*(n-1)
sxy = 2×2
133.7660 276.2553 276.2553 669.9599
sxy = sxy(2,1)
sxy = 276.2553
sxx = var(x)*(n-1)
sxx = 133.7660

More Answers (1)

Voss
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]
Invalid expression. When calling a function or indexing a variable, use parentheses. Otherwise, check for mismatched delimiters.
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 Get Started with MATLAB 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!

Translated by