compute sums by accumulating in a for-loop

1 次查看(过去 30 天)
I am trying to accumulate sums (phi(l) for lags " l"in a for loop given the code below. I keep getting "Unable to perform assignment because the left and right sides have a different number of elements." I have tried multiple ways to try and fix it but nothing is working.
x=normrnd(0,1,100,1);
xprime=detrend(x,'constant');
phi=zeros(14,1);
L= [0:13]';
for l=1:14
phi(l)=(sum(xprime(1:100-l)).*xprime(1+l:100)/(100-(l-1)-1));
end
Unable to perform assignment because the left and right sides have a different number of elements.

采纳的回答

Image Analyst
Image Analyst 2023-12-3
Look at this:
x=normrnd(0,1,100,1);
xprime=detrend(x,'constant');
phi=zeros(14,1);
L= [0:13]';
for l=1:14
temp = (sum(xprime(1:100-l)).*xprime(1+l:100)/(100-(l-1)-1))
fprintf('The size of temp = %d.\n', numel(temp))
phi(l)=(sum(xprime(1:100-l)).*xprime(1+l:100)/(100-(l-1)-1));
end
temp = 99×1
0.0116 0.0105 0.0110 0.0077 -0.0046 -0.0012 -0.0141 0.0183 0.0027 -0.0052
The size of temp = 99.
Unable to perform assignment because the left and right sides have a different number of elements.
So you're trying to stuff 99 values into a slot meant for only one value, phi(l). Not sure how to fix it because I'm not sure what your intent is. Did you mean for phi to be a 99 by 14 matrix and you want to put temp into the columns of phi?
  3 个评论
Image Analyst
Image Analyst 2023-12-3
Watch your parentheses. Maybe you meant either
phi(l) = sum(xprime(1:(100-l)) .* xprime(l:100) / (100-(l-1)-1));
or
phi(l) = sum(xprime(1:(100-l) .* xprime(l:100)) / (100-(l-1)-1);
And l (ell) is not a good variable name - it looks too much like 1 (one) and I (capital I). Use k instead.

请先登录,再进行评论。

更多回答(1 个)

Torsten
Torsten 2023-12-3
编辑:Torsten 2023-12-3
sum(xprime(1:100-l))
This is a scalar.
sum(xprime(1:100-l)).*xprime(1+l:100)
This is a vector of length 100-(1+l)+1.
(sum(xprime(1:100-l)).*xprime(1+l:100)/(100-(l-1)-1))
This remains a vector of length 100-(1+l)+1.
phi(l)
This is s acalar.
Thus you try to assign a vector to a scalar which is not possible.
Maybe you mean
phi(l)=sum(xprime(1:100-l).*xprime(1+l:100))/(100-(l-1)-1));

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by