MATLAB: Covariance between 2 ts over time

covariance loop getelemen

I havea matrix(X) with 3 vectors with 380 elements each. I want to see how the covariance of 1st vector(A) and 2(B) with TS3 (C) evolves over time (25 periods used to compute the cov)
I supposed this should be done by means of a circular loop.
The problem is that the Cov(function) gives a matrix as a result .. and this fact translates into an error in the loop procedure. does someone know if there is a fromula to compute the COV without getting all the cov matrix?
the loop code i've written is :
for i = 26:380
for u = 1:3
covaariances(i,u)= ((cov(X(i,u),x(i,3))))
end
end
this results in an error. could someone of you advise me a way to get what I am aiming for??? thank u for ur valuable time

Best Answer

EDIT
X = rand(1500,50);
% Window size
ws = 25;
% Preallocate
szX = size(X);
covC = cell(szX(1)-24,1);
covM = zeros(szX(1)-24,sx(2));
for n = 1:szX(1)-24
covC{n} = cov(X(0+n:24+n,:));
covM(n,:) = covC{n}(1,:);
end
You can also save on computations by implementing your own covariance calculation for the first series against the other 49 to get a column of values.
Or you can simply save on memory (even though covC is not more than 30 mb) by substituting the "covM line" inside the loop with:
covC{n} = covC{n}(1,:);
and calling outside of the loop:
covC = cat(1,covC{:});