필터 지우기
필터 지우기

compute sums by accumulating in a for-loop

조회 수: 2 (최근 30일)
Kyle
Kyle 2023년 12월 3일
댓글: Kyle 2023년 12월 3일
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.
Kyle
Kyle 2023년 12월 3일
This worked thank you.

댓글을 달려면 로그인하십시오.

추가 답변 (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