Clear Filters
Clear Filters

compute sums by accumulating in a for-loop

2 views (last 30 days)
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.

Accepted Answer

Image Analyst
Image Analyst on 3 Dec 2023
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 Comments
Image Analyst
Image Analyst on 3 Dec 2023
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.

Sign in to comment.

More Answers (1)

Torsten
Torsten on 3 Dec 2023
Edited: Torsten on 3 Dec 2023
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));

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!