How to summation using for loop with a vector

조회 수: 1 (최근 30일)
isaac raggatt
isaac raggatt 2022년 8월 29일
편집: Voss 2022년 8월 29일
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

채택된 답변

Torsten
Torsten 2022년 8월 29일
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

추가 답변 (1개)

Voss
Voss 2022년 8월 29일
편집: Voss 2022년 8월 29일
"... 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

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by