Recursive computation without loop
1 次查看(过去 30 天)
显示 更早的评论
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
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.
采纳的回答
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!