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 Center および File ExchangeMATLAB についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by