Recursive computation without loop

조회 수: 2 (최근 30일)
avenior
avenior 2018년 3월 31일
댓글: avenior 2018년 4월 1일
Hi! Can I write the following code
for j = 2 : N-1
alpha(j+1,:) = A(j,:).*alpha(j,:) + B(j,:);
end
in a form like this:
J = 2:N-1;
alpha(J+1,:) = A(J,:).*alpha(J,:) + B(J,:);
I tried to use this form but the alphas are incorrectly calculated.
  댓글 수: 6
Walter Roberson
Walter Roberson 2018년 4월 1일
You got faster code that calculated the wrong thing.
With the loop the value of B(1,:) affects alpha(2,:), and that has an effect that changes all later output. With the vectorized version you do not get the feedback of earlier B values affecting all later values.
avenior
avenior 2018년 4월 1일
"You got faster code that calculated the wrong thing."
Yes I know. In my code there are other loops that are calculated without using the previous value. I wrote about them.

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

채택된 답변

Walter Roberson
Walter Roberson 2018년 4월 1일
No, values are not stored into the destination until the entire right hand side finishes. Using a vector index on the output does not do an implicit iterative calculation.
If the question is about whether the calculation can be vectorized, the answer is that it can be vectorized for any given length. However the vectorized version is a bit nasty to write out and would be notably slower than the loop.

추가 답변 (0개)

카테고리

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