Is it possible to realize such loop in MATLAB?

1 visualización (últimos 30 días)
Oscar
Oscar el 16 de Sept. de 2024
Comentada: Voss el 16 de Sept. de 2024
Good day, everyone!
For example, we have some x variable.
Is it possible to realize such loop (using "for") to get these results?
1-st iteration: x-1
2-nd iteration: (x-1)*(x-2)
3-rd iteration: (x-1)*(x-2)*(x-3)
etc.

Respuesta aceptada

Voss
Voss el 16 de Sept. de 2024
x = 10;
n_iterations = 5;
results = zeros(1,n_iterations);
r = 1;
for ii = 1:n_iterations
r = r*(x-ii);
results(ii) = r;
end
results
results = 1×5
9 72 504 3024 15120
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
Or, without the loop:
results = cumprod(x-(1:n_iterations))
results = 1×5
9 72 504 3024 15120
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
  2 comentarios
Oscar
Oscar el 16 de Sept. de 2024
Thank you very much!
Voss
Voss el 16 de Sept. de 2024
You're welcome!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by