For loop for Covariance of two vectors

17 ビュー (過去 30 日間)
Caitlin Bemis
Caitlin Bemis 2022 年 9 月 13 日
コメント済み: Caitlin Bemis 2022 年 9 月 13 日
I am looking to make a for loop to identify the individual covariance between each point in two lines and plot them as a color map along a line
To make the for loop I have:
x = rand(1, 5521)
y = rand(1, 5521)
for ii = 1:length(x)
covar(ii) = cov(x,y)
end
I understand that I need to make an empty array to enter the new data into and I understand that I am not calling the covariance to do individual points of the vector, but I am not sure how to fix it.
The plot I want to plot the two variables x and y ontop of eachother with a color map on the bottom showing the differences of variance along the line.

採用された回答

Walter Roberson
Walter Roberson 2022 年 9 月 13 日
Individual covariances between two points is always [0 0; 0 0] because there is a constant relationship between the two scalars. Knowing the one possible input scalar tells you the only possible output for that highly restricted population.
You need at least two x and y in order to get meaningful covariances.
Also remember that covariance between two classes (x, y) is a 2 x 2 array, but you want to color the result, which implies you only want one value per x y rather than 4 values.
  1 件のコメント
Caitlin Bemis
Caitlin Bemis 2022 年 9 月 13 日
Thank you. That makes sense

サインインしてコメントする。

その他の回答 (1 件)

Torsten
Torsten 2022 年 9 月 13 日
編集済み: Torsten 2022 年 9 月 13 日
The covariance between two given vectors is a scalar, namely
cov(x,y) = 1/(n-1) * sum_{i=1}^{i=n} (x(i)-mean(x))*(y(i)-mean(y)):
rng('default')
format long
x = rand(1, 5521);
y = rand(1, 5521);
covariance = 1/5520 * sum((x-mean(x)).*(y-mean(y)))
covariance =
-9.473031297795489e-04
or directly with the matlab function
covariance_matrix = cov(x,y);
covariance = covariance_matrix(2,1)
covariance =
-9.473031297795485e-04
Calculating the covariance between individual data points does not make sense.
Calculating the covariance between random variables is something different.
So I'm not sure what you are trying to do in your code.

カテゴリ

Help Center および File ExchangeAnnotations についてさらに検索

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by