Recursive computation without loop

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 comentarios

Stephen23
Stephen23 el 1 de Abr. de 2018
Editada: Stephen23 el 1 de Abr. de 2018
"Recursive computation without loop"
Recursive calculations do not require loops: loops are iterative.
Why do you want to get rid of the loop: what is the problem with it?
avenior
avenior el 1 de Abr. de 2018
To speed up these calculations. In vector form they are much faster executed.
Stephen23
Stephen23 el 1 de Abr. de 2018
Editada: Stephen23 el 1 de Abr. de 2018
"To speed up these calculations. In vector form they are much faster executed."
How do you know this? It looks to me like premature optimization, which is a classic programming anti-pattern:
avenior
avenior el 1 de Abr. de 2018
Editada: avenior el 1 de Abr. de 2018
"How do you know this?"
Experimentally, I replaced some loops in my code with vector calculations.
Walter Roberson
Walter Roberson el 1 de Abr. de 2018
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 el 1 de Abr. de 2018
"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.

Iniciar sesión para comentar.

 Respuesta aceptada

Walter Roberson
Walter Roberson el 1 de Abr. de 2018

1 voto

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.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Preguntada:

el 31 de Mzo. de 2018

Comentada:

el 1 de Abr. de 2018

Community Treasure Hunt

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

Start Hunting!

Translated by